JavaScript:.forEach()和.map()之间的区别 [英] JavaScript: Difference between .forEach() and .map()
问题描述
我知道有很多这样的话题。我知道基础: .forEach()
在原始数组上运行, .map()
在新数组上运行。
I know that there were a lot of topics like this. And I know the basics: .forEach()
operates on original array and .map()
on the new one.
在我的情况下:
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 ]
我无法理解为什么使用练习
将 b
的值更改为 undefined
。
对不起如果这是一个愚蠢的问题,但我对这种语言很新,我找到的答案到目前为止并没有让我满意。
I can't understand why using practice
changes value of b
to undefined
.
I'm sorry if this is silly question, but I'm quite new in this language and answers I found so far didn't satisfy me.
推荐答案
<他们不是同一个人。让我解释一下这个区别。
They are not one and the same. Let me explain the difference.
foreach
:这会迭代一个列表并对每个操作应用一些带副作用的操作列表成员(例如:将每个列表项保存到数据库)
foreach
: This iterates over a list and applies some operation with side effects to each list member (example: saving every list item to the database)
map
:迭代列表,转换该列表的每个成员,并返回与转换成员相同大小的另一个列表(例如:将字符串列表转换为大写)
map
: This iterates over a list, transforms each member of that list, and returns another list of the same size with the transformed members (example: transforming list of strings to uppercase)
引用
数组.prototype.forEach() - JavaScript | MDN
Array.prototype.map() - JavaScript | MDN
这篇关于JavaScript:.forEach()和.map()之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!