隐居以求其志,行义以达其道
数组迭代器方法
数组迭代器方法

数组迭代器方法

forEach((value, index, arr) =>{}, thisArg?) 稀疏数组中的空白元素不参与,无法提前结束迭代必须遍历完毕,无返回值

map((value, index, arr) =>{}, thisArg?) 返回函数的返回值组成的数组,稀疏数组空白元素不传入函数,但最后的结果包含空白元素,返回的数组长度和原数组长度一致

filter((value, index, arr) =>{}, thisArg?) 返回函数的返回值为true真值的元素组成的数组,稀疏数组空白元素不传入,不影响结果

find((value, index, arr) =>{}, thisArg?) 返回使函数的返回值为true真值的第一个元素,稀疏数组空白元素传入(只是值为undefined),影响结果

findIndex((value, index, arr) =>{}, thisArg?) 返回使函数的返回值为true真值的第一个元素的索引,稀疏数组空白元素传入,影响结果

every((value, index, arr) =>{}, thisArg?) 如果所有元素都使函数返回值为true真值则返回true,否则返回false,会短路提前返回false结束后续迭代,稀疏数组空白元素不传入,不影响结果

some((value, index, arr) =>{}, thisArg?) 如果有一个元素使函数返回值为true真值则返回true,否则返回false,会短路提前返回true结束后续迭代,稀疏数组空白元素不传入,不影响结果

reduce/reduceRight((pre, cur) =>{}, init) 归一数组元素为一个值,稀疏数组空白元素不传入,不影响结果

数组可以包含“空槽”(稀疏数组),这与用值 undefined (不属于稀疏数组)填充的槽不一样。空槽(空白元素)可以用以下方式产生:
// Array 构造函数:
const a = Array(5); // [ <5 empty items> ]

// 数组字面量中的连续逗号:
const b = [1, 2, , , 5]; // [ 1, 2, <2 empty items>, 5 ]

// 直接给大于 array.length 的索引设置值以形成空槽:
const c = [1, 2];
c[4] = 5; // [ 1, 2, <2 empty items>, 5 ]

// 通过直接设置 .length 拉长一个数组:
const d = [1, 2];
d.length = 5; // [ 1, 2, <3 empty items> ]

// 删除一个元素:
const e = [1, 2, 3, 4, 5];
delete e[2]; // [ 1, 2, <1 empty item>, 4, 5 ]

在某些操作中,空槽的行为就像它们被填入了 undefined 那样。
const arr = [1, 2, , , 5]; // 创建一个稀疏数组

// 通过索引访问
console.log(arr[2]); // undefined

// For...of
for (const i of arr) {
  console.log(i);
}

// 输出:1 2 undefined undefined 5

// 展开运算
const another = [...arr]; // "another" 为 [ 1, 2, undefined, undefined, 5 ]

以下代码中也会跳过空槽(空白)元素
// 创建一个稀疏数组
const arr = [1, 2, , , 5]; 

// 属性迭代
const keys = Object.keys(arr);  // [ '0', '1', '4' ]   缺2,3

for (const key in arr) {
  console.log(key);
}
// 输出:'0' '1' '4'

// 在对象中使用展开会跳过(数组中使用展开不会跳过-会变undefined),使用属性枚举,而不是数组的迭代器
const objectSpread = { ...arr }; // { '0': 1, '1': 2, '4': 5 }