常见的伪数组:arguments,getElementsByTagName等获取的NodeList对象
伪数组有以下特点:
- 具有length属性
- 按索引方式存储数据
- 不能使用数组的方法,如push(),pop()等
本质是对象类型,原型指向Obejct
function hello () {
console.log(Object.prototype.toString.call(arguments)) // '[object Arguments]''
console.log(typeof arguments) // 'object'
console.log(arguments.__proto__.constructor === Object) // true
}
hello(1, 2)
伪数组转换为数组的方法
1、Array.from()
function hello() {
console.log(arguments) // Arguments(3)
// 0: 1
// 1: 2
// 2: 3
// callee: ƒ hello()
// length: 3
// Symbol(Symbol.iterator): ƒ values()
// __proto__: Object
let arr = Array.from(arguments)
console.log(arr) // Array(3)
// 0: 1
// 1: 2
// 2: 3
// length: 3
// __proto__: Array(0)
}
hello(1,2,3)
2、Array.prototype.slice.call()
function hello() {
let arr = Array.prototype.slice.call(arguments)
console.log(arr) // [1, 2, 3]
// 0: 1
// 1: 2
// 2: 3
// length: 3
// __proto__: Array(0)
}
hello(1,2,3)
3、展开运算符
function hello() {
let arr = [...arguments]
console.log(arr) // [1, 2, 3]
// 0: 1
// 1: 2
// 2: 3
// length: 3
// __proto__: Array(0)
}
hello(1,2,3)