Javascript 在 for-of 循环中访问 ES6 数组元素索引
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34348937/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Access to ES6 array element index inside for-of loop
提问by Abdennour TOUMI
We can access array elements using a for-of loop:
我们可以使用 for-of 循环访问数组元素:
for (const j of [1, 2, 3, 4, 5]) {
console.log(j);
}
How can I modify this code to access the current index too? I want to achieve this using for-of syntax, neither forEach nor for-in.
如何修改此代码以访问当前索引?我想使用 for-of 语法来实现这一点,既不是 forEach 也不是 for-in。
回答by Micha? Per?akowski
Use Array.prototype.keys
:
for (const index of [1, 2, 3, 4, 5].keys()) {
console.log(index);
}
If you want to access both the key and the value, you can use Array.prototype.entries()
with destructuring:
如果您要访问这两个键和值,可以使用Array.prototype.entries()
与解构:
for (const [index, value] of [1, 2, 3, 4, 5].entries()) {
console.log(index, value);
}
回答by Felix Kling
Array#entries
returns the index and the value, if you need both:
Array#entries
返回索引和值,如果你需要两者:
for (let [index, value] of array.entries()) {
}
回答by chris
In this world of flashy new native functions, we sometimes forget the basics.
在这个充满华丽新本机功能的世界中,我们有时会忘记基础知识。
for (let i = 0; i < arr.length; i++) {
console.log('index:', i, 'element:', arr[i]);
}
Clean, efficient, and you can still break
the loop. Bonus! You can also start from the end and go backwards with i--
!
干净、高效,你仍然可以break
循环。奖金!您也可以从结尾开始,然后使用i--
!
Additional note: If you're using the value a lot within the loop, you may wish to do const value = arr[i];
at the top of the loop for an easy, readable reference.
附加说明:如果您在循环中大量使用该值,您可能希望const value = arr[i];
在循环的顶部做一个简单易读的参考。
回答by Willem van der Veen
In a for..of
loop we can achieve this via array.entries()
. array.entries
returns a new Array iterator object. An iterator object knows how to access items from an iterable one at the time, while keeping track of its current position within that sequence.
在for..of
循环中,我们可以通过array.entries()
. array.entries
返回一个新的数组迭代器对象。迭代器对象当时知道如何从可迭代对象访问项目,同时跟踪其在该序列中的当前位置。
When the next()
method is called on the iterator key value pairs are generated. In these key value pairs the array indexis the key and the array item is the value.
当在next()
迭代器上调用该方法时,会生成键值对。在这些键值对中,数组索引是键,数组项是值。
let arr = ['a', 'b', 'c'];
let iterator = arr.entries();
console.log(iterator.next().value); // [0, 'a']
console.log(iterator.next().value); // [1, 'b']
A for..of
loop is basically a construct which consumes an iterable and loops through all elements (using an iterator under the hood). We can combine this with array.entries()
in the following manner:
甲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);
}
回答by Joseph Merdrignac
in html/js context, on modern browsers, with other iterable objects than Arrays we could also use [Iterable].entries():
在 html/js 上下文中,在现代浏览器中,除了数组之外,还有其他可迭代对象,我们也可以使用 [Iterable].entries():
for(let [index, element] of document.querySelectorAll('div').entries()) {
element.innerHTML = '#' + index
}
回答by TintinSansYeux
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++;
}
回答by Hashbrown
For those using objects that are not an Array
or even array-like, you can build your own iterable easily so you can still use for of
for things like localStorage
which really only have a length
:
对于那些使用不是类Array
或什至类数组的对象的人,您可以轻松构建自己的可迭代对象,因此您仍然可以将其for of
用于localStorage
真正只有一个的对象length
:
function indexerator(length) {
var output = new Object();
var index = 0;
output[Symbol.iterator] = function() {
return {next:function() {
return (index < length) ? {value:index++} : {done:true};
}};
};
return output;
}
Then just feed it a number:
然后只需给它一个数字:
for (let index of indexerator(localStorage.length))
console.log(localStorage.key(index))
回答by solanki...
es6 for...in
es6 for...in
for(const index in [15, 64, 78]) {
console.log(index);
}
回答by Saksham
Another approach could be using Array.prototype.forEach()
as
另一种方法可以使用Array.prototype.forEach()
作为
Array.from({
length: 5
}, () => Math.floor(Math.random() * 5)).forEach((val, index) => {
console.log(val, index)
})
回答by Edwin Felipe
var fruits = ["apple","pear","peach"];
for (fruit of fruits) {
console.log(fruits.indexOf(fruit));
//it shows the index of every fruit from fruits
}
the for loop traverses the array, while the indexof property takes the value of the index that matches the array. P.D this method has some flaws with numbers, so use fruits
for 循环遍历数组,而 indexof 属性获取与数组匹配的索引值。PD这个方法在数字上有一些缺陷,所以用水果