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

  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办法

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理