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


当前回答

我喜欢用这个

function isObject (obj) {
  return typeof(obj) == "object" 
        && !Array.isArray(obj) 
        && obj != null 
        && obj != ""
        && !(obj instanceof String)  }

我认为在大多数情况下,Date必须作为Object通过检查,因此我不会过滤掉日期

其他回答

一个基于Matt Fenwick对其完整答案的第三个选项的NodeJS控制台实验。只要稍微调整一下就能判断真假。

以下对象测试返回false。

> if(Object.getPrototypeOf('v') === Object.prototype){console.log(true);}else{console.log(false);}
false
undefined
> if(Object.getPrototypeOf(1) === Object.prototype){console.log(true);}else{console.log(false);}
false
undefined
> if(Object.getPrototypeOf(false) === Object.prototype){console.log(true);}else{console.log(false);}
false
undefined
> if(Object.getPrototypeOf(['apple']) === Object.prototype){console.log(true);}else{console.log(false);}
false
undefined

对象将返回true。

> if(Object.getPrototypeOf({'this':10}) === Object.prototype){console.log(true);}else{console.log(false);}
true
undefined

我们可以只用一行来检查,这里obj可以是任何值(包括null)

obj?.__proto__ === Object.prototype

or

obj?.constructor.name === 'Object';

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

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

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

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

    <!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>

这很棘手,因为数组是对象类型,函数是对象类型而实际对象{}也是对象类型

问题

const arr = []
const fun = function(){}
const actualObj = {}

arr instanceof Object // true
fun instanceof Object // true
actualObj instanceof Object // true

因此目标是actualObj必须返回true,其他所有值都必须返回false

actualObj instanceof Object && !(actualObj instanceof Array) && !(typeof actualObj === 'function') // true