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


当前回答

这取决于用例,如果我们不想让数组和函数成为Object,我们可以使用undercore.js内置函数。

    function xyz (obj) { 
       if (_.isObject(obj) && !_.isFunction(obj) && !_.isArray(obj)) {
         // now its sure that obj is an object 
       } 
    }

其他回答

function isObjectLike(value) {
  return value != null && typeof value == 'object' && !Array.isArray(value);
}

基于lodash

更新:

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

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

原答覆:

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

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

var isArray=function(value){
    if(Array.isArray){
        return Array.isArray(value);
    }else{
        return Object.prototype.toString.call(value)==='[object Array]';
    }
}
var isObject=function(value){
    return value !== null&&!isArray(value) && typeof value === 'object';
}

var _val=new Date;
console.log(isObject(_val));//true
console.log(Object.prototype.toString.call(_val)==='[object Object]');//false

您可以使用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();
}

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