When iterating through an array with the forEach method, it's common to encounter situations where you want to modify the array's elements. However, attempting to assign new values directly within the callback doesn't always affect the original array.
Consider the following code:
var arr = ["one", "two", "three"]; arr.forEach(function(part) { part = "four"; return "four"; }) alert(arr); // Output: "one,two,three"
Despite the assignment within the callback, the original array arr returns its original values. This happens because forEach creates a shallow copy of the array's elements for the callback function.
To modify an array's elements from a forEach iteration, we need to pass the original array as an additional parameter. This allows us to directly access and modify the array itself within the callback:
arr.forEach(function(part, index, theArray) { theArray[index] = "hello world"; });
By using theArray[index], we can overwrite the original array element.
Alternatively, we can use the second argument of forEach to set the this value within the callback. By setting this to the original array, we can use this[index] to modify the elements directly:
arr.forEach(function(part, index) { this[index] = "hello world"; }, arr); // Use arr as this
Both approaches allow for modifying array elements during iteration. The choice between the two depends on preference.
It's worth mentioning that forEach is one of several array utilities provided by the Array prototype. Other commonly used utilities include:
The above is the detailed content of How do I modify array values within a forEach loop?. For more information, please follow other related articles on the PHP Chinese website!