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


当前回答

出于代码的目的,我找到了与上面的一些答案相对应的决定:

ES6变体:

const checkType = o => Object.prototype
                    .toString
                    .call(o)
                    .replace(/\[|object\s|\]/g, '')
                    .toLowerCase();

ES5变体:

function checkType(o){
   return Object.prototype
                    .toString
                    .call(o)
                    .replace(/\[|object\s|\]/g, '')
                    .toLowerCase();
}

您可以非常简单地使用它:

checkType([]) === 'array'; // true
checkType({}) === 'object'; // true
checkType(1) === 'number'; // true
checkType('') === 'string'; // true
checkType({}.p) === 'undefined'; // true
checkType(null) === 'null'; // true

等等

其他回答

更新:

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

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

原答覆:

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

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

如果typeof yourVariable==“object”,则它是一个对象或null。

如果要排除null、数组或函数,只需执行以下操作:

if (
    typeof yourVariable === 'object' &&
    !Array.isArray(yourVariable) &&
    yourVariable !== null
) {
    executeSomeCode();
}

适用于所有数据类型。它只显示对象

if (data && typeof data === 'object' && !Array.isArray(data)) {
var a = [1]
typeof a //"object"
a instanceof Object //true
a instanceof Array //true

var b ={a: 1}
b instanceof Object //true
b instanceof Array //false

var c = null
c instanceof Object //false
c instanceof Array //false

我被要求提供更多细节。检查变量是否为对象的最简单易懂的方法是myVar类型。它返回一个带有类型的字符串(例如“object”、“undefined”)。

不幸的是,Array和null都有一个类型对象。要仅获取真实对象,需要使用instanceof运算符检查继承链。它将消除null,但Array在继承链中有Object。

因此,解决方案是:

if (myVar instanceof Object && !(myVar instanceof Array)) {
  // code for objects
}

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

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