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()方法不存在这样的问题,它直接返回新的转换后的数组。在这种情况下,建议使用map()方法。

2.链接其他方法

map()方法输出可以与其他方法(如reduce()、sort()、filter())链接在一起,以便在一条语句中执行多个操作。

另一方面,forEach()是一个终端方法,这意味着它不能与其他方法链接,因为它返回undefined。

我们使用以下两种方法找出数组中每个元素的平方和:

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

// 使用 forEach()

const squareUsingForEach = []

let sumOfSquareUsingForEach = 0;

numbers.forEach(x => squareUsingForEach.push(x*

推荐链接

评论可见,请评论后查看内容,谢谢!!!
 您阅读本篇文章共花了: 


大家都在找:

前端框架:前端框架总成英文

架构:架构方案

前端:前端开发需要学什么

大家都在看: