类数组遍历、arguments
类数组的本质是一个对象,只是这个对象模拟出数组的一些特性
let a = {};
let i = 0;
for (i = 0; i < 3; i++) {
a[i] = i
}
a.length = i;
a.splice = Array.prototype.splice;
console.log(a)
/*
Object(3) [0, 1, 2, splice: ƒ]
0: 0
1: 1
2: 2
length: 3
splice: ƒ splice()
*/
类数组和数组的区别:
1、一个是对象,一个是数组
2、数组的length属性当新元素添加到表中的时候会自动更新。类数组如果没有添加push方法则不可以。
3、设置数组的length属性可以扩展数组或者截断数组。
4、因为数组是Array实例所以可以调用Array方法。
arguments
arguments是一个类数组,也就是一个对象,因为本身不带有数组的方法所以比比如forEach | reduce所以叫他类数组。
把数组的方法运用到类数组上面可以使用call和apply的方法
function foo() {
Array.prototype.forEach.call(arguments, (a) => void console.log(a))
}
相当于
function foo() {
arguments.forEach = Array.prototype.forEach;
arguments.forEach((a) => void console.log(a))
}
或者用Array.from把类数组转化成数组
Array.from() 可以通过以下方式来创建数组对象:
- 伪数组对象(拥有一个
length属性和若干索引属性的任意对象) - 可迭代对象(可以获取对象中的元素,如 Map和 Set 等)
function foo() {
const arr = Array.from(arguments)
arr.forEach((item) => {
console.log(item)
})
}
也可以用扩展运算符将arguments转化为数组
function foo() {
const arr = [...arguments];
arr.forEach((item) => {
console.log(item)
})
}
扩展运算符只能用于拥有迭代器的可迭代对象
const a = {};
let i = 0;
for (i = 0; i < 3; i++) {
a[i] = i
}
a.length = i; //拥有length属性可以用于Array.from;
console.log([...a])//报错提示a没有迭代器
//添加迭代器
a[Symbol.iterator] = function * () {
for (let j = 0; j < a.length; j++) {
yield a[i];
}
}
//添加完迭代器之后可以使用扩展运算符
[...a] //[0,1,2]
\