关于javascript:判断一个变量是数组还是对象

2次阅读

共计 710 个字符,预计需要花费 2 分钟才能阅读完成。

  1. 判断的意义?
    首先,后端返回一个变量,前端不分明是数组还是对象
    其次,对象与数组原型链上的 办法 不同 的。
  2. 是否能用 typeof
    不能够。null,数组,对象 ,三者应用typeof() 返回的都是 "object"
    typeof 能够返回的类型为:numberstringbooleanundefinedobjectfunction
typeof(undefined) // "undefined"
typeof(null) // "object"
typeof([1,2]) // "object"
typeof({a:1}) // "object"
typeof('123') // "string"
typeof(1) // "number"
typeof(true)  // "boolean"
typeof(Array) // "function"
typeof(() => {})  // typeof 箭头函数返回也是 "function"
  1. 拓展 typeof()
    谨记 typeof 的返回值都是 string 类型
typeof(typeof(null))   // "string"
typeof(typeof(undefined))  // "string"

typeof(undefined) === undefined // false
typeof(undefined) === "undefined" // true
  1. 如何判断变量是否是数组?
a = []
a instanceof Array // true
a.constructor === Array // true
Array.prototype.isPrototypeOf(arr) // 原型链判断
Array.isArray(arr) // JS 数组办法 Array 中的 isArray 办法
正文完
 0