Check if a value is an object in JavaScript

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

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

30条回答
  •  礼貌的吻别
    2020-11-22 05:39

    For simply checking against Object or Array without additional function call (speed). As also posted here.

    isArray()

    isArray = function(a) {
        return (!!a) && (a.constructor === Array);
    };
    console.log(isArray(        )); // false
    console.log(isArray(    null)); // false
    console.log(isArray(    true)); // false
    console.log(isArray(       1)); // false
    console.log(isArray(   'str')); // false
    console.log(isArray(      {})); // false
    console.log(isArray(new Date)); // false
    console.log(isArray(      [])); // true
    

    isObject() - Note: use for Object literals only, as it returns false for custom objects, like new Date or new YourCustomObject.

    isObject = function(a) {
        return (!!a) && (a.constructor === Object);
    };
    console.log(isObject(        )); // false
    console.log(isObject(    null)); // false
    console.log(isObject(    true)); // false
    console.log(isObject(       1)); // false
    console.log(isObject(   'str')); // false
    console.log(isObject(      [])); // false
    console.log(isObject(new Date)); // false
    console.log(isObject(      {})); // true
    

提交回复
热议问题