如何检查值是否是JavaScript中的对象?


当前回答

如果typeof yourVariable==“object”,则它是一个对象或null。

如果要排除null、数组或函数,只需执行以下操作:

if (
    typeof yourVariable === 'object' &&
    !Array.isArray(yourVariable) &&
    yourVariable !== null
) {
    executeSomeCode();
}

其他回答

一个基于Matt Fenwick对其完整答案的第三个选项的NodeJS控制台实验。只要稍微调整一下就能判断真假。

以下对象测试返回false。

> if(Object.getPrototypeOf('v') === Object.prototype){console.log(true);}else{console.log(false);}
false
undefined
> if(Object.getPrototypeOf(1) === Object.prototype){console.log(true);}else{console.log(false);}
false
undefined
> if(Object.getPrototypeOf(false) === Object.prototype){console.log(true);}else{console.log(false);}
false
undefined
> if(Object.getPrototypeOf(['apple']) === Object.prototype){console.log(true);}else{console.log(false);}
false
undefined

对象将返回true。

> if(Object.getPrototypeOf({'this':10}) === Object.prototype){console.log(true);}else{console.log(false);}
true
undefined

适用于所有数据类型。它只显示对象

if (data && typeof data === 'object' && !Array.isArray(data)) {

有点晚了。。。对于“普通对象”(我的意思是,像{'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”。:)

这是一个可选链接的答案,也许是这个问题的最小isObj函数。

常量isObj=o=>o?。构造函数==对象;//这是真的console.log(isObj({}));//对象//这些都是假的console.log(isObj(0));//数字console.log(isObj([]));//大堆console.log(isObj('ol'));//一串console.log(isObj(null));//无效的console.log(isObj(未定义));//未定义console.log(isObj(()=>{}));//作用console.log(isObj(对象));//班

试试这个

if (objectName instanceof Object) {
  alert('Not an object');
}
else {
  alert('An object');
}