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


当前回答

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

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

其他回答

试试这个

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

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

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

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

好的,在回答问题之前,让我们先给你这个概念,在JavaScript中,函数是Object,也可以是null、Object、Array甚至Date,所以正如你所看到的,没有一种简单的方法像typeof obj==“Object”,所以上面提到的一切都会返回true,但是有一些方法可以通过编写函数或使用JavaScript框架来检查它,好的:

现在,假设您有一个真正的对象(不是null、函数或数组):

var obj = {obj1: 'obj1', obj2: 'obj2'};

纯JavaScript:

//that's how it gets checked in angular framework
function isObject(obj) {
  return obj !== null && typeof obj === 'object';
}

or

//make sure the second object is capitalised 
function isObject(obj) {
   return Object.prototype.toString.call(obj) === '[object Object]';
}

or

function isObject(obj) {
    return obj.constructor.toString().indexOf("Object") > -1;
}

or

function isObject(obj) {
    return obj instanceof Object;
}

您可以简单地在代码中使用上述函数之一,方法是调用它们,如果它是一个对象,则返回true:

isObject(obj);

如果您使用的是JavaScript框架,他们通常会为您准备这些类型的函数,其中很少:

jQuery:

 //It returns 'object' if real Object;
 jQuery.type(obj);

角度:

angular.isObject(obj);

Undercore和Lodash:

//(NOTE: in Underscore and Lodash, functions, arrays return true as well but not null)
_.isObject(obj);

请记住,new Date()的类型是“object”。

因此,如果要查找{key:value}对象,日期对象是无效的。

最后:o=>o&&typeof o==“对象”&&!在我看来,(o instance of Date)是对你问题的更好回答。

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

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