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


当前回答

好的,在回答问题之前,让我们先给你这个概念,在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);

其他回答

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

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

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

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

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

这是一个老问题,但我想把它留在这里。大多数人都在检查变量是否为{},这意味着一个键值配对,而不是JavaScript用于给定对象的下划线构造,因为老实说,JavaScript中的大部分内容都是一个对象。所以把它从路上拿开。如果你这样做。。。

let x = function() {}
typeof x === 'function' //true
x === Object(x) // true
x = []
x === Object(x) // true

// also
x = null
typeof null // 'object'

大多数时候,我们想要的是知道我们是否有来自API的资源对象或从ORM返回的数据库调用。然后,我们可以测试是否不是数组、是否为null、是否为“function”类型、是否为Object

// To account also for new Date() as @toddmo pointed out

x instanceof Object && x.constructor === Object

x = 'test' // false
x = 3 // false
x = 45.6 // false
x = undefiend // false
x = 'undefiend' // false
x = null // false
x = function(){} // false
x = [1, 2] // false
x = new Date() // false
x = {} // true

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

if(typeof value === 'object' && value.constructor === Object)
{
    console.log("This is an object");
}