kec
kec

Reputation: 2149

Use for-of to assign to the elements of an array

Is there any way to use a for-of loop to assign to elements of an iterable? Something like this, where it actually will change the values of the elements in the array.

for (let e of some_array) {
    e = new_value;
}

Upvotes: 0

Views: 31

Answers (1)

Felix Kling
Felix Kling

Reputation: 816840

You can use Array#entries() to get the array element and the index:

for (let [i, e] of some_array.entries()) {
    some_array[i] = new_value;
}

But in such a case I would probably just stick with a normal for loop or use Array#map.

Upvotes: 2

Related Questions