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]
3 Answers
Reset to default 4item
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);
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745311607a4622024.html
评论列表(0条)