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]
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);
本文标签: using forEach to apply a function to each array item in javascriptStack Overflow
版权声明:本文标题:using forEach to apply a function to each array item in javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745311606a2652959.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论