If I have a null array and want to loop an object over every entry, but it doesn't work on the function loops. Example:
const myArray = [null, null, null]
myArray.forEach(e => e = {}); // a console.log reveals that the loop is running 3 times
console.log(myArray); // expected: [{}, {}, {}] reality: [null, null, null]
for(let e of myArray) {
e = {}; // a console.log reveals that the loop is running 3 times
}
console.log(myArray); // expected: [{}, {}, {}] reality: [null, null, null]
classic for works:
for(let i = 0; i < myArray.length; i++) {
myArray[i] = {};
}
console.log(myArray); // expected: [{}, {}, {}] reality: [{}, {}, {}]
Do I overlook something obvious?
Fundamentally, when you do:
let e = myArray[someIndex];
...you're copying the value from myArray[someIndex]
to e
. There is no ongoing link at that point between e
and the array element, it's just that they have the same value. Both forEach
and for-of
, in different ways, are fundamentally doing the above. Assigning to e
, in either case, won't have any effect on the array element e
's value came from. It's exactly like:
let a = 1;
let b = a; // This does not create any kind of link back to `a`...
let b = 42; // So this doesn't change `a`.
If you want to replace every element of an array:
If you want to update the array in place, use a classic for
loop as you have in your question, or anything similar that gives you an index, and use that index to write to myArray[index]
.
or
To create a new array of the updated values, use map
:
const newArray = myArray.map((e) => /*....*/);