如何检查值是否是JavaScript中的对象?
当前回答
当其他一切都失败时,我使用这个:
var isObject = function(item) {
return item.constructor.name === "Object";
};
其他回答
这很棘手,因为数组是对象类型,函数是对象类型而实际对象{}也是对象类型
问题
const arr = []
const fun = function(){}
const actualObj = {}
arr instanceof Object // true
fun instanceof Object // true
actualObj instanceof Object // true
因此目标是actualObj必须返回true,其他所有值都必须返回false
actualObj instanceof Object && !(actualObj instanceof Array) && !(typeof actualObj === 'function') // true
这取决于你所说的“是一个物体”。如果您想要所有非原语的内容,即可以设置新财产的内容,那么这应该可以做到:
function isAnyObject(value) {
return value != null && (typeof value === 'object' || typeof value === 'function');
}
它排除了基元(纯数字/NaN/Infinity、纯字符串、符号、true/false、undefined和null),但其他所有对象(包括Number、Boolean和String对象)都应返回true。注意,JS没有定义当与typeof一起使用时,应该返回哪些“主机”对象,例如窗口或控制台,因此很难用这样的检查来覆盖这些对象。
如果您想知道某个对象是“普通”对象,即它是作为文本{}创建的还是使用object.create(null)创建的,您可以这样做:
function isPlainObject(value) {
if (Object.prototype.toString.call(value) !== '[object Object]') {
return false;
} else {
var prototype = Object.getPrototypeOf(value);
return prototype === null || prototype === Object.prototype;
}
}
编辑2018:因为Symbol.toStringTag现在允许自定义Object.protoct.toString.call(…)的输出,所以上面的isPlainObject函数在某些情况下可能会返回false,即使对象以文本形式开始其生命。可以说,按照惯例,带有自定义字符串标记的对象不再是纯对象,但这进一步模糊了Javascript中的纯对象定义。
Object.pr原型.toString.call(myVar)将返回:
“[object object]”如果myVar是对象“[object Array]”如果myVar是数组等
有关这方面的更多信息,以及为什么它是typeof的一个很好的替代品,请查看本文。
如果明确希望检查给定值是否为{}。
function isObject (value) {
return value && typeof value === 'object' && value.constructor === Object;
}
有点晚了。。。对于“普通对象”(我的意思是,像{'x':5,'y':7}),我有一个小片段:
function isPlainObject(o) {
return (o === null || Array.isArray(o) || typeof o == 'function' || o.constructor === Date ) ?
false
:(typeof o == 'object');
}
它生成下一个输出:
console.debug(isPlainObject(isPlainObject)); //function, false
console.debug(isPlainObject({'x': 6, 'y': 16})); //literal object, true
console.debug(isPlainObject(5)); //number, false
console.debug(isPlainObject(undefined)); //undefined, false
console.debug(isPlainObject(null)); //null, false
console.debug(isPlainObject('a')); //string, false
console.debug(isPlainObject([])); //array?, false
console.debug(isPlainObject(true)); //bool, false
console.debug(isPlainObject(false)); //bool, false
它总是适用于我。只有当“o”的类型是“object”,但没有null、数组或函数时,If才会返回“true”。:)