首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在for of循环中访问当前数量的i?

如何在for of循环中访问当前数量的i?
EN

Stack Overflow用户
提问于 2015-11-05 15:36:34
回答 4查看 1.3K关注 0票数 17

给定一个for of循环,赋值的变量(本例中为i)的值等于如果它是一个普通的for循环,array[i]将等于的值。如何访问i当前所在的数组的索引。

我想要的

代码语言:javascript
复制
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. 
}
EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2015-11-05 15:41:13

没什么简单的..。如果你想“简单访问”数组中的循环中的项和索引,可以使用forEach,例如

代码语言:javascript
复制
array.forEach(function(item, index) { 
... 
});

或者作为T.J.Crowder的指针(我错过了ES6标签)

代码语言:javascript
复制
array.forEach((item, index) => { 
    ... 
});

像许多编程语言一样,javascript有多种方法来做类似的事情,技巧在于为工作选择正确的工具。

票数 15
EN

Stack Overflow用户

发布于 2015-11-05 16:27:01

您可以使用entries函数。它将为数组中的每个条目返回一个索引/值对,如下所示:

代码语言:javascript
复制
[0, "one"]
[1, "two"]
[2, "three"]

将其与array destructuring结合使用,可将每个条目解析为相应的变量名:

代码语言:javascript
复制
const arr = ["one", "two", "three"]
for(const [index, value] of arr.entries()) {
  console.log(index, value);
}

Babel REPL Example

票数 25
EN

Stack Overflow用户

发布于 2015-11-05 15:43:01

你是说这个吗?

代码语言:javascript
复制
array = ["one", "two", "three"];

for (i = 0; i < array.length; i++) {
  console.log(i); // Logs the current index number;
  console.log(array[i]); // Logs the index matching in the array;
}

来自Kaiido的一个很好的comment是,您可以使用它直接从数组中获取值作为变量。

代码语言:javascript
复制
for (var ind = 0, i=array[ind]; ind < array.length; i=array[++ind]) {
    console.log(i);
    console.log(ind);
}
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33538944

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档