admin管理员组

文章数量:1420112

I am trying to understand how forEach works in 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]. But get [5, 4, 3, 2, 1]

I am trying to understand how forEach works in 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]. But get [5, 4, 3, 2, 1]

Share Improve this question asked Aug 1, 2014 at 5:33 user544079user544079 16.6k42 gold badges120 silver badges172 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 4

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. 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/jfriend00/L8598/


You may want to note that .map() is made for producing a new array for operations like this:

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

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

var newArray = arr.map(square);

Working demo: http://jsfiddle/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. 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

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

item is a local variable, assigning to it does not alter the array. To modify the array, you'd have to assign to the property arr[i], for example

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:

new_arr = arr.map(square);

本文标签: using forEach to apply a function to each array item in javascriptStack Overflow