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 ?
Best Answer
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 ofthis
in each call to the callback:That second example shows
arr
itself being set up asthis
in 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;this
will beundefined
if that second argument is not provided.(Note: the above stuff about
this
does not apply if the callback is a=>
function, becausethis
is 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:
forEach
for doing a thing with or to every entry in an array;filter
for producing a new array containing only qualifying entries;map
for making a one-to-one new array by transforming an existing array;some
to check whether at least one element in an array fits some description;every
to check whether all entries in an array match a description;find
to look for a value in an arrayand so on. MDN link