我们可以使用for-of循环访问数组元素:
For (const j of [1,2,3,4,5]) { console.log (j); }
我如何修改这段代码来访问当前索引?我想使用for-of语法来实现这一点,既不是forEach也不是for-in。
我们可以使用for-of循环访问数组元素:
For (const j of [1,2,3,4,5]) { console.log (j); }
我如何修改这段代码来访问当前索引?我想使用for-of语法来实现这一点,既不是forEach也不是for-in。
当前回答
数组#entries返回索引和值,如果你需要两者:
for (let [index, value] of array.entries()) {
}
其他回答
您还可以使用JavaScript来解决您的问题
迭代(item, index) { Console.log (' ${item}有索引${index} '); //做你想做的… } readJsonList () { jsonList.forEach (this.iterate); //它可以是任何数组列表。 }
你可以尝试使用里面的indexOf方法。循环
let arrData = [15, 64, 78] for (arrData的const数据){ console.log(“数据值”,数据,“数据索引”,arrData.indexOf(数据)); }
使用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(指数、价值); }
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,索引) })