简体   繁体   English

在for-of循环中更改项目的值

[英]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. 我正在学习ES6中的一些新技巧,并且我非常喜欢数组的for-of循环。 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: 例如在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. 在ES6中使用for-of循环时,如果我在循环内更改当前项目的值,则不会反映在数组中。 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 : 如果您还需要循环for … of的数组迭代中的索引,请使用.entries()方法

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. 如果只对索引感兴趣而没有值,则可以迭代myArr .keys()

Not with for-of , no. 没有for-of ,不。 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. 在这种情况下,如果您想就地更新数组,则forEach可能是一个更好的选择;如果您愿意创建一个新数组,或者是一个很好的老式for循环,则map可能是一个更好的选择。

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); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM