如何检查值是否是JavaScript中的对象?
当前回答
underscore.js提供了以下方法来确定某个对象是否真的是对象:
_.isObject = function(obj) {
return obj === Object(obj);
};
更新
由于V8之前的一个bug和轻微的微速度优化,自underscore.js 1.7.0(2014年8月)以来,该方法如下:
_.isObject = function(obj) {
var type = typeof obj;
return type === 'function' || type === 'object' && !!obj;
};
其他回答
您可以使用JSON.stringify来测试Object,如下所示:
var测试={}if(JSON.stringify(测试)[0]==“{”){console.log('这是一个对象')}
简单的工作解决方案:
function isObject(value) {
return !(value instanceof Date) && !Array.isArray(value) && !Object.is(value, null) && !Object.is(value, undefined) && !(value instanceof Function)
}
Object.pr原型.toString.call(myVar)将返回:
“[object object]”如果myVar是对象“[object Array]”如果myVar是数组等
有关这方面的更多信息,以及为什么它是typeof的一个很好的替代品,请查看本文。
有点晚了。。。对于“普通对象”(我的意思是,像{'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”。:)
试试这个
if (objectName instanceof Object) {
alert('Not an object');
}
else {
alert('An object');
}