我知道有很多这样的话题。我知道基本原理:. 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“创建一个新数组,其中包含对该数组中的每个元素调用所提供的函数的结果。”

forEach实际上不返回任何东西。它只是为每个数组元素调用函数,然后就完成了。所以无论你在被调用的函数中返回什么都会被丢弃。

另一方面,map将类似地为每个数组元素调用函数,但它不会丢弃它的返回值,而是捕获它并构建一个包含这些返回值的新数组。

这也意味着你可以在使用forEach的任何地方使用map,但你仍然不应该这样做,这样你就不会毫无目的地收集返回值。如果你不需要它们,不收集它们会更有效率。

其他回答

数组中。forEach“对每个数组元素执行一次所提供的函数。” 数组中。Map“创建一个新数组,其中包含对该数组中的每个元素调用所提供的函数的结果。”

forEach实际上不返回任何东西。它只是为每个数组元素调用函数,然后就完成了。所以无论你在被调用的函数中返回什么都会被丢弃。

另一方面,map将类似地为每个数组元素调用函数,但它不会丢弃它的返回值,而是捕获它并构建一个包含这些返回值的新数组。

这也意味着你可以在使用forEach的任何地方使用map,但你仍然不应该这样做,这样你就不会毫无目的地收集返回值。如果你不需要它们,不收集它们会更有效率。

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

读:

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

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

forEach() map()
Functionality Performs given operation on each element of the array Performs given "transformation" on a "copy" of each element
Return value Returns undefined Returns new array with transformed elements, leaving back original array unchanged.
Preferrable usage scenario and example Performing non-tranformation like processing on each element.

For example, saving all elements in the database.
Obtaining array containing output of some processing done on each element of the array.

For example, obtaining array of lengths of each string in the array

forEach()例子

chars = ['Hello', 'world!!'); var retVal = char . foreach(函数(字){ console.log(" save to db: " + word) }) console.log (retVal) / /定义

map()例子

chars = ['Hello', 'world!!'); Var长度= char .map(函数(单词){ 返回word.length }) console.log(长度)/ /(5、8)

Foreach和map的区别:

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

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

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

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

它们不是一回事。让我来解释一下其中的区别。

forEach:它遍历一个列表,并对每个列表成员应用一些具有副作用的操作(例如:将每个列表项保存到数据库),并且不返回任何东西。

map:遍历一个列表,转换该列表的每个成员,并返回另一个与转换后的成员相同大小的列表(例如:将字符串列表转换为大写)。它不会改变被调用的数组(尽管回调函数可能会这样做)。

参考文献

Array.prototype.forEach() - JavaScript | MDN

Array.prototype.map() - JavaScript | MDN