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


当前回答

const isObject = function(obj) {
  const type = typeof obj;
  return type === 'function' || type === 'object' && !!obj;
};

!!obj是检查obj是否正确(以过滤空值)的简写

其他回答

确定变量是否为Object的最简单方法:

第一个:评估对象的类型

第二个:从Object获取Array属性必须返回undefined(例如,长度是一个Array属性,它不适用于Object)

so:

if (_object instanceof Object && _object.length === undefined) {
// here you can be sure that you have a curly bracket object :)
}

如果您想检查对象的原型是否仅来自object。过滤掉字符串、数字、数组、参数等。

function isObject (n) {
  return Object.prototype.toString.call(n) === '[object Object]';
}

或作为单个表达式箭头函数(ES6+)

const isObject = n => Object.prototype.toString.call(n) === '[object Object]'

当其他一切都失败时,我使用这个:

var isObject = function(item) {
   return item.constructor.name === "Object";
}; 

更新:

这个答案是不完整的,给出了误导性的结果。例如,null也被认为是JavaScript中的对象类型,更不用说其他几种边缘情况。遵循下面的建议,然后转到其他“最支持(和正确!)的答案”:

typeof yourVariable === 'object' && yourVariable !== null

原答覆:

尝试使用typeof(var)和/或var instanceof。

编辑:这个答案给出了如何检查变量财产的思路,但它并不是检查它是否是一个对象的万无一失的方法(毕竟根本没有方法。

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