访问for-of循环内的ES6数组元素索引

Abd*_*UMI 194 javascript ecmascript-6 for-of-loop

我们可以使用for-of循环访问数组元素:

for (const j of [1, 2, 3, 4, 5]) {
  console.log(j);
}
Run Code Online (Sandbox Code Playgroud)

如何修改此代码以访问当前索引?我想使用for-of语法实现这一点,既不是forEach也不是for-in.

Mic*_*ski 295

用途Array.prototype.keys:

for (const index of [1, 2, 3, 4, 5].keys()) {
  console.log(index);
}
Run Code Online (Sandbox Code Playgroud)

如果要同时访问键和值,可以使用Array.prototype.entries()解构:

for (const [index, value] of [1, 2, 3, 4, 5].entries()) {
  console.log(index, value);
}
Run Code Online (Sandbox Code Playgroud)

  • 如果有人想知道,我用`.entries()`测试`for-of`,与`.forEach()相比,它慢了两倍.https://jsperf.com/for-of-vs-foreach-with-index (55认同)
  • 不幸的是,我需要从嵌套循环中产生.不能使用forEach,因为该函数会为`yield`关键字创建范围问题.但我需要访问我的用例的索引,所以...基本的旧`;;`循环它,我猜. (3认同)
  • @K48 很高兴知道,如果您想在 es 中获得最快的速度,请使用“反向循环”:https://www.incredible-web.com/blog/performance-of-for-loops-with-javascript/ (2认同)
  • @KyleBaker和`.entires()`for-for循环有什么问题? (2认同)

Fel*_*ing 274

Array#entries 如果需要,则返回索引和值:

for (let [index, value] of array.entries()) {

}
Run Code Online (Sandbox Code Playgroud)

  • 使用TypeScript:'TS2495:Type IterableIterator不是数组类型或字符串类型'.似乎这样就可以解决了:https://github.com/Microsoft/TypeScript/pull/12346 (3认同)
  • 此外,不支持Internet Explorer. (2认同)
  • 真好!这似乎也可以与const一起使用。 (2认同)
  • @Steven:如果你不需要索引,你可以只做`for(var值of document.styleSheets){}`.如果你确实需要索引,你可以首先通过`Array.from`:`for(let [index,value] of Array.from(document.styleSheets)){}`将值转换为数组. (2认同)

chr*_*ris 21

在这个华丽的新本土功能的世界里,我们有时会忘记基础知识.

for (let i = 0; i < arr.length; i++) {
    console.log('index:', i, 'element:', arr[i]);
}
Run Code Online (Sandbox Code Playgroud)

干净,高效,你仍然可以break循环.奖金!您也可以从最后开始,然后向后退i--!

  • 你仍然可以`break`一个`for-of`和`for(let [index,value] of array.entries())`更容易阅读.向后退就像添加`.reverse()`一样简单. (4认同)
  • 顺便说一下条件应该是这样的 - > for(let i = 0; i <arr.length; i ++)没有(-1)或者它不会循环遍历数组的所有元素. (2认同)
  • 我认为这是对这个问题的完全可接受的答案。永远不会是公认的答案,但是它已经帮助数十个人或更多人搜索了该问题。这就是SO的目的。 (2认同)
  • 简单的 `for` 循环比 `for of array.entries()` 快约 8 倍。https://jsbench.me/6dkh13vqrr/1 (2认同)

Sak*_*ham 6

另一种方法可以使用Array.prototype.forEach()as

Array.from({
  length: 5
}, () => Math.floor(Math.random() * 5)).forEach((val, index) => {
  console.log(val, index)
})
Run Code Online (Sandbox Code Playgroud)


Msu*_*ven 6

You can also handle index yourself if You need the index, it will not work if You need the key.

let i = 0;
for (const item of iterableItems) {
  // do something with index
  console.log(i);

  i++;
}
Run Code Online (Sandbox Code Playgroud)


Wil*_*een 5

for..of循环中,我们可以通过array.entries(). array.entries返回一个新的数组迭代器对象。迭代器对象当时知道如何从可迭代对象访问项目,同时跟踪其在该序列中的当前位置。

当在next()迭代器上调用该方法时,会生成键值对。在这些键值对中,数组索引是键,数组项是值。

let arr = ['a', 'b', 'c'];
let iterator = arr.entries();
console.log(iterator.next().value); // [0, 'a']
console.log(iterator.next().value); // [1, 'b']
Run Code Online (Sandbox Code Playgroud)

for..of环是基本上消耗可迭代,并通过所有的元素(使用罩下一个迭代)环路的构建体。我们可以array.entries()通过以下方式将其与此结合:

array = ['a', 'b', 'c'];

for (let indexValue of array.entries()) {
  console.log(indexValue);
}


// we can use array destructuring to conveniently
// store the index and value in variables
for (let [index, value] of array.entries()) {
   console.log(index, value);
}
Run Code Online (Sandbox Code Playgroud)