In JavaScript, arrays are immutable, meaning their elements cannot be directly modified within loop iterations.
var arr = ["one", "two", "three"]; arr.forEach(function(part) { part = "four"; return "four"; }) alert(arr);
However, this code will still output ["one", "two", "three"] because part is a local variable within the callback function that does not directly modify the array.
To modify the array elements during iteration, access them using the element's index or the this object:
// Using index arr.forEach(function(part, index, theArray) { theArray[index] = "hello world"; }); // Using 'this' arr.forEach(function(part, index) { this[index] = "hello world"; }, arr);
In the second example, arr is specified as the this value of the callback function. Thus, this[index] refers to the array element.
Instead of forEach, consider using other functions that modify arrays in a more direct way:
These functions provide efficient mechanisms for manipulating arrays without the need for direct element modification during iteration.
The above is the detailed content of Can You Modify Array Elements in JavaScript During Iteration?. For more information, please follow other related articles on the PHP Chinese website!