Reputation: 1564
var arr = [1, 5, 17];
for (let e of arr)
e += 3; // Does nothing
arr.forEach(e => e += 3); // Does nothing
console.log(arr);
In the above code my aim was to set all elements to 0 (just as an example), yet, when I use =
on the element variable, nothing changes. I suspect this is, because
One solution is arr.forEach((e, i, a) => a[i] = 0);
, but this looks very suboptimal when compared to a simple for
of
loop. Also, I've heard that arr.forEach
in general has worse performance.
Upvotes: 0
Views: 40
Reputation: 386660
Just for setting all items to the same primitive value, or with an object to the same reference, you could use Array#fill
var array = [1, 5, 17];
array.fill(0);
console.log(array);
Upvotes: 0
Reputation: 5797
const input = [1, 5, 17]
const output = input.map(e => 0)
console.log(output)
Upvotes: 3