我试图了解 forEach 在 Javascript 中的工作原理
var arr = [5,4,3,2,1];
var square = function(x){
return x * x;
}
arr.forEach(function(item){
item = square(item);
});
我应该得到[25,16,9,4,1]
。但得到 [5, 4, 3, 2, 1]
最佳答案
item
只是回调函数的一个参数(其工作方式类似于局部变量),修改它不会更改数组 - 它不是实际的数组元素。回调的接下来两个参数为您提供数组和索引,以便您可以修改实际的数组元素。
var arr = [5,4,3,2,1];
var square = function(x){
return x * x;
}
arr.forEach(function(item, index, array){
array[index] = square(item);
});
工作演示:http://jsfiddle.net/jfriend00/L8598/
您可能需要注意 .map()
是为了为如下操作生成新数组:
var arr = [5,4,3,2,1];
var square = function(x){
return x * x;
}
var newArray = arr.map(square);
关于javascript - 使用 forEach 将函数应用于 JavaScript 中的每个数组项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25073455/