javascriptarraysforeachpass-by-reference

change values in array when doing foreach


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 ?


Solution

  • The callback is passed the element, the index, and the array itself.

    arr.forEach(function(part, index, theArray) {
      theArray[index] = "hello world";
    });
    

    edit — as noted in a comment, the .forEach() function can take a second argument, which will be used as the value of this in each call to the callback:

    arr.forEach(function(part, index) {
      this[index] = "hello world";
    }, arr); // use arr as this
    

    That second example shows arr itself being set up as this in the callback.One might think that the array involved in the .forEach() call might be the default value of this, but for whatever reason it's not; this will be undefined if that second argument is not provided.

    (Note: the above stuff about this does not apply if the callback is a => function, because this 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:

    and so on. MDN link