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


当前回答

我有一段代码片段可以使用。当没有给出整段代码时,我觉得很困惑,所以我自己创建了它:

    <!DOCTYPE html>
    <html>
    <body>
    <button onclick="myFunc()">Try it</button>

    <script>
    var abc = new Number();
    // var abc = 4;
    //this is a code variation which will give a diff alert

    function myFunc()
    {
    if(abc && typeof abc === "object")
    alert('abc is an object and does not return null value');
    else
    alert('abc is not an object');
    }
    </script>

    </body>
    </html>

其他回答

简单的工作解决方案:

function isObject(value) {
    return !(value instanceof Date) && !Array.isArray(value) && !Object.is(value, null) && !Object.is(value, undefined) && !(value instanceof Function)
}

有点晚了。。。对于“普通对象”(我的意思是,像{'x':5,'y':7}),我有一个小片段:

function isPlainObject(o) {
   return (o === null || Array.isArray(o) || typeof o == 'function' || o.constructor === Date ) ?
           false
          :(typeof o == 'object');
}

它生成下一个输出:

console.debug(isPlainObject(isPlainObject)); //function, false
console.debug(isPlainObject({'x': 6, 'y': 16})); //literal object, true
console.debug(isPlainObject(5)); //number, false
console.debug(isPlainObject(undefined)); //undefined, false
console.debug(isPlainObject(null)); //null, false
console.debug(isPlainObject('a')); //string, false
console.debug(isPlainObject([])); //array?, false
console.debug(isPlainObject(true)); //bool, false
console.debug(isPlainObject(false)); //bool, false

它总是适用于我。只有当“o”的类型是“object”,但没有null、数组或函数时,If才会返回“true”。:)

哦,我的上帝!我认为这可能比以往任何时候都要短,让我们看看:

短代码和最终代码

函数isObject(obj){返回obj!=null&&obj.constructor.name==“对象”}console.log(isObject({}))//返回trueconsole.log(isObject([]))//返回falseconsole.log(isObject(null))//返回false

解释

退货类型

typeof JavaScript对象(包括null)返回“object”

console.log(类型为null,类型为[],类型为{})

检查其构造函数

检查其构造函数属性会返回带有其名称的函数。

console.log(({}).cconstructor)//返回名为“Object”的函数console.log(([]).cconstructor)//返回名为“Array”的函数console.log((null).cconstructor)//引发错误,因为null实际上没有属性

Function.name简介

Function.name返回函数的只读名称或闭包的“匿名”。

console.log(({}).cconstructor.name)//返回“Object”console.log(([]).cconstructor.name)//返回“Array”console.log((null).cconstructor.name)//引发错误,因为null实际上没有属性

注意:截至2018年,Function.name可能无法在IE中工作https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#Browser_compatibility

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.pr原型.toString.call(myVar)将返回:

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

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