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方法
Object.prototype.toString.call(a) // Object原型上的toString方法,返回[object constructorName]的字符串格式
  1. 然而instanceof.constructor有弊端,在通过iframeArray构造函数,new一个数组对象下会失效
let a = []

// iframe 元素会创建包含另外一个文档的内联框架
var iframe = document.createElement("iframe")
document.body.append(iframe)

// 通过window.frames获取所有iframe元素组成的数组
// 取到iframe的Array构造函数,赋值给xArray
var xArray = window.frames[window.frames.length - 1].Array

// 通过iframe的Array构造函数,new一个数组对象
var arr = new xArray(1, 2, 3)

console.log(arr instanceof Array) // false
console.log(arr.constructor === Array) // false

corn6
4 声望0 粉丝

寻找自我Corn6