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

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

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


当前回答

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

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

其他回答

你可以尝试使用里面的indexOf方法。循环

let arrData = [15, 64, 78] for (arrData的const数据){ console.log(“数据值”,数据,“数据索引”,arrData.indexOf(数据)); }

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

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

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

数组#entries返回索引和值,如果你需要两者:

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

}