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?
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?
Share Improve this question asked Dec 29, 2016 at 16:25 Shane_ILShane_IL 3451 gold badge5 silver badges18 bronze badges 8-
3
Why not use
map
? You don't need to mutate the array, you can transform the data! – elclanrs Commented Dec 29, 2016 at 16:26 -
This isn't a
for of
loop. – Andy Ray Commented Dec 29, 2016 at 16:27 -
3
for of
is an additional way to iterate over arrays. It doesn't remove the old ones. Use it when it's convenient, that's all. – Denys Séguret Commented Dec 29, 2016 at 16:27 -
1
Note that there's what I assume is a typo in the question, you're missing
.length
ini < myArr;
. – T.J. Crowder Commented Dec 29, 2016 at 16:30 -
For next time, I remend showing the construct you're asking about (in this case,
for-of
), to avoid having lots of people misread the question. – T.J. Crowder Commented Dec 29, 2016 at 16:43
2 Answers
Reset to default 15If 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.
Not with for-of
, no. You don't have the index of the item, and writing to your variable has no effect on the original array.
You could hack it:
let index = 0;
for (const v of myArr) {
if (/*...some condition...*/) {
myArr[index] = "moo";
}
++index;
}
...and that works, because of the definition of the array iterator, but it's pretty verbose. In that case, forEach
might be a better choice if you want to update the array in-place, or map
if you're happy to create a new array, or a good old-fashioned for
loop.
Gratuitous example of the above (also showing that it works with sparse arrays, because of the way the array iterator is defined):
let myArr = [1,2,3];
myArr[10] = "sparse"; // Just to prove it works
console.log("before", myArr);
let index = 0;
for (const v of myArr) {
if (v === "sparse") {
myArr[index] = "moo";
}
++index;
}
console.log("after", myArr);