我知道有很多这样的话题。我知道基本原理:. foreach()操作原始数组,.map()操作新数组。

在我的例子中:

function practice (i){
    return i+1;
};

var a = [ -1, 0, 1, 2, 3, 4, 5 ];
var b = [ 0 ];
var c = [ 0 ];
console.log(a);
b = a.forEach(practice);
console.log("=====");
console.log(a);
console.log(b);
c = a.map(practice);
console.log("=====");
console.log(a);
console.log(c);

这是输出:

[ -1, 0, 1, 2, 3, 4, 5 ]
=====
[ -1, 0, 1, 2, 3, 4, 5 ]
undefined
=====
[ -1, 0, 1, 2, 3, 4, 5 ]
[ 0, 1, 2, 3, 4, 5, 6 ]

我不明白为什么使用practice会改变b的值为undefined。 如果这是一个愚蠢的问题,我很抱歉,但我对这门语言很陌生,到目前为止我找到的答案并不能让我满意。


当前回答

Foreach和map的区别:

Map():如果你使用Map,那么Map可以通过迭代主数组返回新的数组。

Foreach():如果你使用Foreach,那么它不能为每个can迭代主数组返回任何东西。

有用的链接:使用这个链接来理解差异

https://codeburst.io/javascript-map-vs-foreach-f38111822c0f

其他回答

这里没有提到的一个穿梭的区别是forEach()可以在静态(不是活动的)NodeList上循环,而map()不能

//works perfectly
      document.querySelectorAll('.score').forEach(element=>console.log(element));
    
    
  //Uncaught TypeError: document.querySelectorAll(...).map is not a function        
      document.querySelectorAll('.score').map(element=>console.log(element));

你需要知道的主要区别是.map()返回一个新数组,而. foreach()不返回。这就是为什么在输出中会看到这种差异。. foreach()只是对数组中的每个值进行操作。

读:

Array.prototype.forEach() - JavaScript | MDN Array.prototype.map() - JavaScript | MDN

你可能还想看看: - Array.prototype.every() - JavaScript | MDN

.map和. foreach会做同样的事情,直到你开始对拥有数百万个元素的数组进行操作。.map会创建另一个具有相同大小(可能还有类型,这取决于数组的种类)的集合,这可能会占用大量内存。

性能分析(同样-不是很科学) 根据我的经验,有时候.map()比.foreach()更快。

let rows = []; for (let i = 0; i < 10000000; i++) { // console.log("here", i) rows.push({ id: i, title: 'ciao' }); } const now1 = Date.now(); rows.forEach(row => { if (!row.event_title) { row.event_title = `no title ${row.event_type}`; } }); const now2 = Date.now(); rows = rows.map(row => { if (!row.event_title) { row.event_title = `no title ${row.event_type}`; } return row; }); const now3 = Date.now(); const time1 = now2 - now1; const time2 = now3 - now2; console.log('forEach time', time1); console.log('.map time', time2);

在我的macbook pro上(2013年底)

在1909年 .map时间444

forEach()和map()的区别

forEach()只是循环遍历元素。它会丢弃返回值并且总是返回undefined。此方法的结果不提供输出。

Map()循环遍历元素,通过迭代主数组分配内存并存储返回值

例子:

   var numbers = [2,3,5,7];

   var forEachNum = numbers.forEach(function(number){
      return number
   })
   console.log(forEachNum)
   //output undefined

   var mapNum = numbers.map(function(number){
      return number
   })
   console.log(mapNum)
   //output [2,3,5,7]

map()比forEach()快