我们可以使用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。
当前回答
另一种方法是使用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(指数、价值); }
es6的……
for(const index in [15, 64, 78]) {
console.log(index);
}
只需在循环之前创建一个变量并分配一个整数值。
设index = 0;
然后使用加法赋值运算符进入循环作用域
指数+= 1;
就是这样,检查下面的代码片段示例。
设index = 0; For (const j of [1,2,3,4,5]) { console.log(指数,指数); 指数+= 1; }
你可以尝试使用里面的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,索引) })