Check if a value is an object in JavaScript

后端 未结 30 3366
臣服心动
臣服心动 2020-11-22 05:06

How do you check if a value is an object in JavaScript?

30条回答
  •  孤独总比滥情好
    2020-11-22 05:47

    This will work. It is a function that returns true, false, or possibly null.

    const isObject = obj => obj && obj.constructor && obj.constructor === Object;
    
    console.log(isObject({})); // true
    console.log(isObject([])); // false
    console.log(isObject(new Function)); // false
    console.log(isObject(new Number(123))); // false
    console.log(isObject(null)); // null

提交回复
热议问题