Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing the value of an item in a for-of loop

I'm learning some of the new tricks in ES6, and I quite like the for-of loop for arrays. One thing I'm having some trouble with is if I want to manipulate the current item's value inside the loop.

For example in ES5:

var myArr = [1,2,3];
for(var i = 0; i < myArr; i++){
    myArr[i] = "moo"
}

When using the for-of loop in ES6 if I change the value of the current item inside the loop it's not reflected in the array. Is there a way to do this?

like image 946
Shane_IL Avatar asked Dec 07 '22 20:12

Shane_IL


1 Answers

If you also need the index in an array iteration with a for … of loop, use the .entries() method:

const myArr = [1,2,3];
for (const [i, el] of myArr.entries()) {
    myArr[i] = "moo" + el;
}

If you're only interested in the indices and no values, you could iterate myArr.keys() instead.

like image 95
Bergi Avatar answered Jan 01 '23 12:01

Bergi