Home >Web Front-end >JS Tutorial >Why does modifying array elements within a forEach loop in JavaScript not change the original array?
In JavaScript, the forEach() method is commonly used to iterate over an array and perform certain actions on each element. However, attempts to modify these elements within the iteration loop often result in the original values being preserved.
Consider the following example:
var arr = ["one", "two", "three"]; arr.forEach(function (part) { part = "four"; return "four"; }); alert(arr); // Output: ["one", "two", "three"]
Despite assigning "four" to part within the loop, the arr array remains unchanged. This is because the forEach() callback only receives a copy of each element, not a reference to the original element.
To achieve meaningful modifications, we can utilize the index parameter provided by the forEach() callback. This parameter represents the index of the current element in the array:
arr.forEach(function (part, index, theArray) { theArray[index] = "hello world"; });
In this case, theArray refers to the original array, and we can access and modify its elements directly using the index value.
Alternatively, we can use the this parameter of the forEach() callback as a reference to the array:
arr.forEach(function (part, index) { this[index] = "hello world"; }, arr); // Use arr as this
By setting arr as the value of this, we ensure that this[index] points to the correct element within the array.
While forEach() allows for iteration and modification, there are other Array prototype methods that may be better suited for specific use cases:
By selecting the appropriate method based on your task, you can achieve efficient and accurate array manipulation.
The above is the detailed content of Why does modifying array elements within a forEach loop in JavaScript not change the original array?. For more information, please follow other related articles on the PHP Chinese website!