跳到主要内容

数组遍历

JavaScript 中多种数组遍历方法。

for 循环

const arr = [1, 2, 3, 4, 5];

// 传统 for 循环
for (let i = 0; i < arr.length; i++) {
console.log(i, arr[i]);
}

// for...of (推荐)
for (const item of arr) {
console.log(item);
}

// 带索引的 for...of
for (const [index, item] of arr.entries()) {
console.log(index, item);
}

forEach

const arr = [1, 2, 3, 4, 5];

arr.forEach((item, index, array) => {
console.log(`索引 ${index}: ${item}`);
});

// 使用 thisArg
arr.forEach(function(item) {
console.log(this.prefix + item);
}, { prefix: '值:' });

map - 转换数组

const numbers = [1, 2, 3, 4, 5];

// 平方
const squared = numbers.map(n => n * n);
// [1, 4, 9, 16, 25]

// 对象数组转换
const users = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' }
];

const names = users.map(u => u.name);
// ['Alice', 'Bob']

filter - 过滤数组

const numbers = [1, 2, 3, 4, 5, 6];

// 偶数
const evens = numbers.filter(n => n % 2 === 0);
// [2, 4, 6]

// 大于 3 的数
const greaterThan3 = numbers.filter(n => n > 3);
// [4, 5, 6]

reduce - 累积计算

const numbers = [1, 2, 3, 4, 5];

// 求和
const sum = numbers.reduce((acc, cur) => acc + cur, 0);
// 15

// 求最大值
const max = numbers.reduce((acc, cur) => Math.max(acc, cur), 0);
// 5

// 数组转对象
const arr = ['a', 'b', 'c'];
const obj = arr.reduce((acc, cur, i) => {
acc[cur] = i;
return acc;
}, {});
// { a: 0, b: 1, c: 2 }

some / every

const arr = [1, 2, 3, 4, 5];

// 是否有偶数
const hasEven = arr.some(n => n % 2 === 0);
// true

// 是否都是正数
const allPositive = arr.every(n => n > 0);
// true