如何在 for of 循环中访问 i 的当前数量? [英] How can the current number of i be accessed in a for of loop?
问题描述
给定一个 for of 循环,分配的变量的值(在这个例子中为 i
)等于 array[i]
如果它是一个正常的for 循环.如何访问 i
当前所在的数组的索引.
Given a for of loop the value of the assigned the variable(i
for this example) is equal to what array[i]
would equal if it was a normal for loop. How can the index of the array the that i
is currently on be accessed.
我想要什么
let array = ["one", "two", "three"];
for (let i of array) {
console.log(i);// normally logs cycle one : "one", cycle two : "two", cycle three : "three".
console.log(/*what equals the current index*/);// what I want to log cycle one : 1, cycle two : 2, cycle three : 3.
}
推荐答案
没有什么简单的...如果你想简单地访问"数组循环中的项和索引,请使用 forEach代码> 例如
nothing simple ... if you want "simple access" to both the item and the index in a loop over an array, use forEach
e.g.
array.forEach(function(item, index) {
...
});
或作为 T.J.Crowder 指针出问题(我错过了 ES6 标签)
or as T.J. Crowder pointer out (and I missed the ES6 tag)
array.forEach((item, index) => {
...
});
像许多编程语言一样,javascript 有多种方法可以做类似的事情,技巧在于为工作选择合适的工具
like many programming languages, javascript has multiple ways to do similar things, the skill is in choosing the right tool for the job
这篇关于如何在 for of 循环中访问 i 的当前数量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!