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

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

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


当前回答

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

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

    element.innerHTML = '#' + index

}

其他回答

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

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

    element.innerHTML = '#' + index

}

es6的……

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

另一种方法是使用Array.prototype.forEach() as

Array.from ({ 长度:5 }, () => Math.floor(Math.random() * 5))。forEach((val, index) => { console.log (val,索引) })

使用Array.prototype.keys:

对于[1,2,3,4,5].keys()的const索引{ console.log(指数); }

如果你想同时访问键和值,你可以使用Array.prototype.entries()进行解构:

For (const [index, value] of [1,2,3,4,5].entries()) { console.log(指数、价值); }

您还可以使用JavaScript来解决您的问题

迭代(item, index) { Console.log (' ${item}有索引${index} '); //做你想做的… } readJsonList () { jsonList.forEach (this.iterate); //它可以是任何数组列表。 }