访问循环的内部的ES6数组元素索引



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

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

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

使用Array.prototype.keys:

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

如果您想同时访问密钥和值,可以使用带析构函数的Array.prototype.entries()

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

Array#entries返回索引和值(如果需要两者):

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

在这个充斥着华而不实的新原生函数的世界里,我们有时会忘记一些基本功能。

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

干净,高效,你仍然可以break循环。奖金你也可以从最后开始,用i--倒退!

额外注意:如果您在循环中经常使用该值,您可能希望在循环顶部执行const value = arr[i];,以获得简单易读的参考。

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

当对next()方法进行调用时,会生成迭代器键值对。在这些键值对中,数组索引是键,数组项是值。

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

如果您需要索引,您也可以自己处理索引,如果您需要键,它将不起作用。

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

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

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

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

for(let [index, element] of document.querySelectorAll('div').entries()) {
    element.innerHTML = '#' + index
}

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

let index = 0;

然后在循环范围中使用加法赋值运算符

index += 1;

这就是它,查看下面的片段示例。

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

对于那些使用不是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))

您可以尝试在。。。环路

let arrData = [15, 64, 78]
for (const data of arrData) {
  console.log("data value", data, "index of data ", arrData.indexOf(data));
}

您还可以使用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.
}   

es6 for...in

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

最新更新