js数组中map和forEach的区别

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循环中断遍历

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值