面试题 -- 如何判断一个变量是数组还是对象

2019-04-22  本文已影响0人  开着五菱宏光的小白

typeof

        var a = [1,2,3]
        var b = {
            c: 1
        }
        console.log(typeof a)
        console.log(typeof b)

结果都是Object


instanceof

        var a = [1,2,3]
        var b = {
            c: 1
        }
        console.log(a instanceof Array)      //true
        console.log(a instanceof Object)     //true
        console.log(b instanceof Array)      //false
        console.log(b instanceof Object)     //true

数组也是对象


constructor

  var a = [1,2,3]
        var b = {
            c: 1
        }
        console.log(a.constructor === Array)      //true
        console.log(a.constructor === Object)     //true
        console.log(b.constructor === Array)      //false
        console.log(b.constructor === Object)     //true  


Object.prototype.toString.call()

     var a = [1,2,3]
        var b = {
            c: 1
        }
        console.log(Object.prototype.toString.call(a))      //[object Array]
        console.log(Object.prototype.toString.call(b))      //[object Object]

Object.prototype.toString.call()结果更加精准


上一篇下一篇

猜你喜欢

热点阅读