我们可以使用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。
当前回答
在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(指数、价值); }
其他回答
在html/js上下文中,在现代浏览器中,对于数组以外的其他可迭代对象,我们也可以使用[iterable].entries():
for(let [index, element] of document.querySelectorAll('div').entries()) {
element.innerHTML = '#' + index
}
在这个花哨的新本地函数的世界里,我们有时会忘记基本的东西。
for (let i = 0; i < arr.length; i++) {
console.log('index:', i, 'element:', arr[i]);
}
干净,高效,你仍然可以打破循环。奖金!你也可以从结尾开始,用i——!
额外注意:如果你在循环中经常使用这个值,你可能希望执行const value = arr[i];在循环的顶部为一个简单的,可读的参考。
另一种方法是使用Array.prototype.forEach() as
Array.from ({ 长度:5 }, () => Math.floor(Math.random() * 5))。forEach((val, index) => { console.log (val,索引) })
您还可以使用JavaScript来解决您的问题
迭代(item, index) { Console.log (' ${item}有索引${index} '); //做你想做的… } readJsonList () { jsonList.forEach (this.iterate); //它可以是任何数组列表。 }
在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(指数、价值); }