example:
var arr = ["one","two","three"];
arr.forEach(function(part){
part = "four";
return "four";
})
alert(arr);
The array is still with it’s original values, is there any way to have writing access to array’s elements from iterating function ?
The callback is passed the element, the index, and the array itself.
edit — as noted in a comment, the
.forEach()function can take a second argument, which will be used as the value ofthisin each call to the callback:That second example shows
arritself being set up asthisin the callback.One might think that the array involved in the.forEach()call might be the default value ofthis, but for whatever reason it’s not;thiswill beundefinedif that second argument is not provided.(Note: the above stuff about
thisdoes not apply if the callback is a=>function, becausethisis never bound to anything when such functions are invoked.)Also it’s important to remember that there is a whole family of similar utilities provided on the Array prototype, and many questions pop up on Stackoverflow about one function or another such that the best solution is to simply pick a different tool. You’ve got:
forEachfor doing a thing with or to every entry in an array;filterfor producing a new array containing only qualifying entries;mapfor making a one-to-one new array by transforming an existing array;someto check whether at least one element in an array fits some description;everyto check whether all entries in an array match a description;findto look for a value in an arrayand so on. MDN link