我们可以使用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。
当前回答
你可以尝试使用里面的indexOf方法。循环
let arrData = [15, 64, 78] for (arrData的const数据){ console.log(“数据值”,数据,“数据索引”,arrData.indexOf(数据)); }
其他回答
你可以尝试使用里面的indexOf方法。循环
let arrData = [15, 64, 78] for (arrData的const数据){ console.log(“数据值”,数据,“数据索引”,arrData.indexOf(数据)); }
如果你需要索引,你也可以自己处理索引,如果你需要键,它将不起作用。
let i = 0;
for (const item of iterableItems) {
// do something with index
console.log(i);
i++;
}
使用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(指数、价值); }
数组#entries返回索引和值,如果你需要两者:
for (let [index, value] of array.entries()) {
}
在for..of循环中,我们可以通过array.entries()实现这一点。数组中。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()结合起来:
数组= ['a', 'b', 'c']; for (let indexValue of array.entries()) { console.log (indexValue); } //我们可以使用数组解构来方便 //在变量中存储索引和值 For (let [index, value] of array.entries()) { console.log(指数、价值); }