- 判断的意义?
首先,后端返回一个变量,前端不清楚是数组还是对象;
其次,对象与数组原型链上的方法是不同的。 - 是否能用
typeof
?
不可以。null,数组,对象
,三者使用typeof()
返回的都是"object"
typeof
可以返回的类型为:number
、string
、boolean
、undefined
、object
、function
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"
- 拓展
typeof()
谨记typeof
的返回值都是string
类型
typeof(typeof(null)) // "string"
typeof(typeof(undefined)) // "string"
typeof(undefined) === undefined // false
typeof(undefined) === "undefined" // true
- 如何判断变量是否是数组?
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]的字符串格式
- 然而
instanceof
和.constructor
有弊端,在通过iframe
的Array
构造函数,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
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。