rsk82 rsk82 - 4 months ago 11
Javascript Question

is it possible to change values of the array when doing foreach in javascript?

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 ?

Answer

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

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