Check if a value is an object in JavaScript

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

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

30条回答
  •  醉梦人生
    2020-11-22 05:52

    For the purpose of my code I found out this decision which corresponds with some of the answers above:

    ES6 variant:

    const checkType = o => Object.prototype
                        .toString
                        .call(o)
                        .replace(/\[|object\s|\]/g, '')
                        .toLowerCase();
    

    ES5 variant:

    function checkType(o){
       return Object.prototype
                        .toString
                        .call(o)
                        .replace(/\[|object\s|\]/g, '')
                        .toLowerCase();
    }
    

    You can use it very simply:

    checkType([]) === 'array'; // true
    checkType({}) === 'object'; // true
    checkType(1) === 'number'; // true
    checkType('') === 'string'; // true
    checkType({}.p) === 'undefined'; // true
    checkType(null) === 'null'; // true
    

    and so on..

提交回复
热议问题