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


当前回答

Ramda函数库具有检测JavaScript类型的出色功能。

完整功能的释义:

function type(val) {
  return val === null      ? 'Null'      :
         val === undefined ? 'Undefined' :
         Object.prototype.toString.call(val).slice(8, -1);
}

当我意识到解决方案是多么简单和美丽时,我不得不笑了。

Ramda文档中的用法示例:

R.type({}); //=> "Object"
R.type(1); //=> "Number"
R.type(false); //=> "Boolean"
R.type('s'); //=> "String"
R.type(null); //=> "Null"
R.type([]); //=> "Array"
R.type(/[A-z]/); //=> "RegExp"
R.type(() => {}); //=> "Function"
R.type(undefined); //=> "Undefined"

其他回答

您可以使用Object.prototype的toString()方法轻松完成此操作

if(Object.prototype.toString.call(variable) == "[object Object]"){
   doSomething();
}

or

if(Object.prototype.toString.call(variable).slice(8,-1).toLowerCase() == "object"){
   doSomething();
}

更新:

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

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

原答覆:

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

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

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

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

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

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

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

只需检查对象或数组,无需额外的函数调用(速度)。同样张贴在这里。

isArray()

isArray = function(a) {
    return (!!a) && (a.constructor === Array);
};
console.log(isArray(        )); // false
console.log(isArray(    null)); // false
console.log(isArray(    true)); // false
console.log(isArray(       1)); // false
console.log(isArray(   'str')); // false
console.log(isArray(      {})); // false
console.log(isArray(new Date)); // false
console.log(isArray(      [])); // true

isLiteralObject()-注意:仅用于Object文本,因为它对自定义对象(如newDate或newYourCustomObject)返回false。

isLiteralObject = function(a) {
    return (!!a) && (a.constructor === Object);
};
console.log(isLiteralObject(        )); // false
console.log(isLiteralObject(    null)); // false
console.log(isLiteralObject(    true)); // false
console.log(isLiteralObject(       1)); // false
console.log(isLiteralObject(   'str')); // false
console.log(isLiteralObject(      [])); // false
console.log(isLiteralObject(new Date)); // false
console.log(isLiteralObject(      {})); // true