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


当前回答

Object.pr原型.toString.call(myVar)将返回:

“[object object]”如果myVar是对象“[object Array]”如果myVar是数组等

有关这方面的更多信息,以及为什么它是typeof的一个很好的替代品,请查看本文。

其他回答

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

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

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

lodash有isPlainObject,这可能是许多来到这个页面的人都在寻找的。当给定函数或数组时,它返回false。

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;
};

一个基于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

如果明确希望检查给定值是否为{}。

function isObject (value) {
 return value && typeof value === 'object' && value.constructor === Object;
}