简体   繁体   English

使用forEach将函数应用于javascript中的每个数组项

[英]using forEach to apply a function to each array item in javascript

I am trying to understand how forEach works in Javascript 我试图了解forEach在Javascript中是如何工作的

var arr = [5,4,3,2,1];

var square = function(x){
   return x * x;
}

arr.forEach(function(item){
     item = square(item);
});

I should get [25, 16, 9, 4, 1] . 我应该得到[25, 16, 9, 4, 1] But get [5, 4, 3, 2, 1] 但得到[5, 4, 3, 2, 1]

item is just an argument to your callback function (that works like a local variable) and modifying it does not change the array - it is not the actual array element. item只是你的回调函数的一个参数(就像一个局部变量一样),修改它不会改变数组 - 它不是实际的数组元素。 The next two arguments to the callback give you the array and the index so you could modify the actual array element. 回调的下两个参数为您提供数组和索引,以便您可以修改实际的数组元素。

var arr = [5,4,3,2,1];

var square = function(x){
   return x * x;
}

arr.forEach(function(item, index, array){
     array[index] = square(item);
});

Working demo: http://jsfiddle.net/jfriend00/L8598/ 工作演示: http//jsfiddle.net/jfriend00/L8598/


You may want to note that .map() is made for producing a new array for operations like this: 您可能需要注意.map()用于为此类操作生成新数组:

var arr = [5,4,3,2,1];

var square = function(x){
   return x * x;
}

var newArray = arr.map(square);

Working demo: http://jsfiddle.net/jfriend00/C226B/ 工作演示: http//jsfiddle.net/jfriend00/C226B/

That is because you are not collecting the results in any variable. 那是因为你没有在任何变量中收集结果。 The variable item is being changed in the local scope of function. 变量item在本地函数范围内被更改。 To get that result outside you have to collect that in a variable. 要获得该结果,您必须在变量中收集该结果。

Do like bellow 像吼叫一样

var arr = [5,4,3,2,1];
var result = [];

var square = function(x){
   return x * x;
}

arr.forEach(function(item){
     item = square(item);// 
     result.push(item);
});

Seems like for your above situation map is a better solution 似乎对于您的上述情况, map是一个更好的解决方案

 arr.map(square) //will return expected result.

item is a local variable, assigning to it does not alter the array. item是一个局部变量,赋值给它不会改变数组。 To modify the array, you'd have to assign to the property arr[i] , for example 要修改数组,您必须分配给属性arr[i] ,例如

arr.forEach(function(item, i) {
    arr[i] = square(item);
});

However, what you really want to do is a map that won't modify anything, but produce a new array of the results: 但是,您真正想要做的是一个不会修改任何内容的map ,而是生成一个新的结果数组:

new_arr = arr.map(square);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM