isObject
检查传入的值是否为对象或函数
/**
* 检查传入的值是否为对象或函数。
*
* @param {*} obj - 要检查的值
* @returns {boolean} 如果值是对象或函数,返回 true;否则返回 false
* @example
* // 返回 true
* isObject({})
* isObject([])
* isObject(function(){})
*
* @example
* // 返回 false
* isObject(null)
* isObject(42)
* isObject("string")
*/
export default function isObject(obj) {
/**
* typeof null === 'object',所以需要额外判断
* typeof obj 返回 obj 的类型:
* - 对于对象,返回 'object'
* - 对于函数,返回 'function'
* - 对于其他类型(如数字、字符串),返回相应的类型名
* 函数返回两种情况为 true:
* - type === 'function':如果传入的是函数
* - type === 'object' && !!obj:如果传入的是对象且不是 null
* !!obj 部分确保对象不为 null:
* - 在 JavaScript 中,typeof null 返回 'object'
* - !!obj 会将 null 转换为 false
* - 非 null 的对象会转换为 true
*/
var type = typeof obj;
return type === 'function' || (type === 'object' && !!obj);
}最后更新于