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


当前回答

如果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>

如果明确希望检查给定值是否为{}。

function isObject (value) {
 return value && typeof value === 'object' && value.constructor === Object;
}

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

问题

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
function isObjectLike(value) {
  return value != null && typeof value == 'object' && !Array.isArray(value);
}

基于lodash

有点晚了。。。对于“普通对象”(我的意思是,像{'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”。:)