给定一个for of循环,赋值的变量(本例中为i
)的值等于如果它是一个普通的for循环,array[i]
将等于的值。如何访问i
当前所在的数组的索引。
我想要的
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.
}
发布于 2015-11-05 15:41:13
没什么简单的..。如果你想“简单访问”数组中的循环中的项和索引,可以使用forEach
,例如
array.forEach(function(item, index) {
...
});
或者作为T.J.Crowder的指针(我错过了ES6标签)
array.forEach((item, index) => {
...
});
像许多编程语言一样,javascript有多种方法来做类似的事情,技巧在于为工作选择正确的工具。
发布于 2015-11-05 16:27:01
您可以使用entries函数。它将为数组中的每个条目返回一个索引/值对,如下所示:
[0, "one"]
[1, "two"]
[2, "three"]
将其与array destructuring结合使用,可将每个条目解析为相应的变量名:
const arr = ["one", "two", "three"]
for(const [index, value] of arr.entries()) {
console.log(index, value);
}
发布于 2015-11-05 15:43:01
你是说这个吗?
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是,您可以使用它直接从数组中获取值作为变量。
for (var ind = 0, i=array[ind]; ind < array.length; i=array[++ind]) {
console.log(i);
console.log(ind);
}
https://stackoverflow.com/questions/33538944
复制相似问题