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

时间:2015-12-18 05:15:28

标签: javascript ecmascript-6 for-of-loop

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

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

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

12 个答案:

答案 0 :(得分:263)

使用Array.prototype.keys

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

如果您想同时访问密钥和值,可以将Array.prototype.entries()destructuring一起使用:

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

答案 1 :(得分:258)

如果您需要两者,

Array#entries将返回索引和值:

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

}

答案 2 :(得分:17)

在这个崭新的本机函数世界中,有时我们会忘记基础知识。

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

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

附加说明:如果您在循环中大量使用该值,则不妨在循环顶部进行const value = arr[i];,以获取易于理解的参考。

答案 3 :(得分:4)

如果需要索引,也可以自己处理索引,如果需要,则无法使用。

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

  i++;
}

答案 4 :(得分:3)

在html / js上下文中,在现代浏览器上,除了Arrays之外我们也可以使用[Iterable] .entries():

for(let [index, element] of document.querySelectorAll('div').entries()) {

    element.innerHTML = '#' + index

}

答案 5 :(得分:1)

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

在迭代器上调用next()方法时,将生成键值对。在这些键值对中,数组 index 是键,而数组项是值。

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

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);
}

答案 6 :(得分:1)

只需在循环之前创建一个变量并分配一个整数值即可。

let index = 0;

然后使用 addition assignment operator 进入循环范围

index += 1;

就是这样,检查下面的代码片段示例。

let index = 0;
for (const j of [1, 2, 3, 4, 5]) {
  index += 1;
  console.log('index ',index);
}

答案 7 :(得分:0)

对于那些使用非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;
}

然后只输入一个数字:

for (let index of indexerator(localStorage.length))
    console.log(localStorage.key(index))

答案 8 :(得分:0)

es6 for...in

for(const index in [15, 64, 78]) {                        
    console.log(index);
}

答案 9 :(得分:0)

另一种方法可能是使用Array.prototype.forEach()作为

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

答案 10 :(得分:0)

您还可以使用JavaScript解决问题

iterate(item, index) {
    console.log(`${item} has index ${index}`);
    //Do what you want...
}

readJsonList() {    
    jsonList.forEach(this.iterate);
    //it could be any array list.
}   

答案 11 :(得分:-3)

var fruits = ["apple","pear","peach"];
for (fruit of fruits) {
    console.log(fruits.indexOf(fruit));
    //it shows the index of every fruit from fruits
}

for循环遍历数组,而indexof属性采用与数组匹配的索引值。 P.D这种方法在数字上有一些缺陷,因此请使用水果