判断一个变量是数组还是对象

秒速五厘米 2023-08-17 16:42 230阅读 0赞
  1. 使用 instanceof
  2. 使用 isArray

    var arr = []
    var obj = {}

    // instanceof
    function ins(arr) {

    1. if (arr instanceof Array) {
    2. console.log('is array')
    3. } else {
    4. console.log('not array')

    }
    }
    ins(arr) // ‘is array’
    ins(obj) // ‘not array’

    // isArray
    function is(arr) {
    if (Array.isArray(arr)) {

    1. console.log('is array')

    } else {

    1. console.log('not array')

    }
    }
    is(arr) // ‘is array’
    is(obj) // ‘not array’

转载于:https://www.cnblogs.com/0x29a/p/11240874.html

发表评论

表情:
评论列表 (有 0 条评论,230人围观)

还没有评论,来说两句吧...

相关阅读