foreach()和map()通常都是用来遍历array元素,主要有以下几个区别
1 返回值
const arr = [1, 2, 3, 4, 5];
function test() {
arr.forEach((v) => {
return v
});
}
console.log(test());//undefined
forEach没有返回值,只针对每个元素调用func。
forEach()无法在所有元素遍历完成前,终止遍历,或者return 跳出当前循环,
这样的话,使用return失效,空循环就会显示undefined
const numbers = [1, 2, 3, 4, 5];
// 使用 forEach()
const squareUsingForEach = [];
numbers.forEach(x => squareUsingForEach.push(x * x));
// 使用 map()
const squareUsingMap = numbers.map(x => x * x);
console.log(squareUsingForEach); // [1, 4, 9, 16, 25]
console.log(squareUsingMap); // [1, 4, 9, 16, 25]
由于forEach()返回undefined,所以我们需要传递一个空数组来创建一个新的转换后的数组。map()方法不存在这样的问题,它直接返回新的转换后的数组
2 链接其他方法
map()方法输出可以与其他方法(如reduce()、sort()、filter())链接在一起,以便在一条语句中执行多个操作。
const numbers = [1, 2, 3, 4, 5];
// 使用 forEach()
const squareUsingForEach = []
let sumOfSquareUsingForEach = 0;
numbers.forEach(x => squareUsingForEach.push(x * x));
squareUsingForEach.forEach(v => sumOfSquareUsingForEach += v);
// 使用 map()
const sumOfSquareUsingMap = numbers.map(x => x * x).reduce((total, value) => total + value);
console.log(sumOfSquareUsingForEach); // 55
console.log(sumOfSquareUsingMap); // 55
3 中断遍历
const numbers = [1, 2, 3, 4, 5];
// break; inside forEach()
const squareUsingForEach = [];
numbers.forEach(x => {
if(x == 3) break; // <- SyntaxError
squareUsingForEach.push(x*x);
});
// break; inside map()
const squareUsingMap = numbers.map(x => {
if(x == 3) break; // <- SyntaxError
return x*x;
});
可使用for循环中断遍历