Post Self
Post Self

Reputation: 1564

How to take variables by reference in a for loop?

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

Answers (3)

Nina Scholz
Nina Scholz

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

user8471893
user8471893

Reputation:

Use this

arr.forEach(e,i => arr[i] = 0);

Upvotes: 0

Arman Charan
Arman Charan

Reputation: 5797

Try Array.prototype.map()

const input = [1, 5, 17]
const output = input.map(e => 0)
console.log(output)

Upvotes: 3

Related Questions