js数组操作中,map()和forEach()的区别

*** Array.prototype.map()和Array.prototype.forEach()的定义。

forEach(): 针对每一个元素执行提供的函数。除了抛出异常以外,没有办法中止或跳出 forEach() 循环。如果你需要中止或跳出循环,forEach() 方法不是应当使用的工具。
map(): 创建一个新的数组,其中每一个元素由调用数组中的每一个元素执行提供的函数得来。map 方法会给原数组中的每个元素都按顺序调用一次 callback 函数。callback 每次执行后的返回值(包括 undefined)组合起来形成一个新数组。 callback 函数只会在有值的索引上被调用;那些从来没被赋过值或者使用 delete 删除的索引则不会被调用。

const array1 = [1, 4, 9, 16];
// pass a function to map
const map1 = array1.map(x => x * 2);
console.log(map1);
console.log(array1);
// expected output: Array [2, 8, 18, 32]
// expected output: Array [1, 4, 9, 16]

////////////////////////////////////////

const array1 = ['a', 'b', 'c'];
const resultForEach = array1.forEach(element => console.log(element));
console.log(resultForEach);
console.log(array1)
// expected output: "a"
// expected output: "b"
// expected output: "c"
// expected output: undefiend
// expected output: ['a', 'b', 'c'];

 

    ***共同点

  • 都是循环遍历数组中的每一项

  • 每一次执行匿名函数都支持三个参数,数组中的当前项item,当前项的索引index,原始数组input

  • 匿名函数中的this都是指window

  • 只能遍历数组

    ***差异点

     map()有返回值,forEach()没有

posted @ 2025-11-19 09:52  大萨特  阅读(11)  评论(0)    收藏  举报