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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With