如何检查值是否是JavaScript中的对象?
当前回答
试试这个
if (objectName instanceof Object) {
alert('Not an object');
}
else {
alert('An object');
}
其他回答
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”。:)
function isObjectLike(value) {
return value != null && typeof value == 'object' && !Array.isArray(value);
}
基于lodash
适用于所有数据类型。它只显示对象
if (data && typeof data === 'object' && !Array.isArray(data)) {
出于代码的目的,我找到了与上面的一些答案相对应的决定:
ES6变体:
const checkType = o => Object.prototype
.toString
.call(o)
.replace(/\[|object\s|\]/g, '')
.toLowerCase();
ES5变体:
function checkType(o){
return Object.prototype
.toString
.call(o)
.replace(/\[|object\s|\]/g, '')
.toLowerCase();
}
您可以非常简单地使用它:
checkType([]) === 'array'; // true
checkType({}) === 'object'; // true
checkType(1) === 'number'; // true
checkType('') === 'string'; // true
checkType({}.p) === 'undefined'; // true
checkType(null) === 'null'; // true
等等