Abd*_*UMI 194 javascript ecmascript-6 for-of-loop
我们可以使用for-of循环访问数组元素:
for (const j of [1, 2, 3, 4, 5]) {
console.log(j);
}
Run Code Online (Sandbox Code Playgroud)
如何修改此代码以访问当前索引?我想使用for-of语法实现这一点,既不是forEach也不是for-in.
Mic*_*ski 295
for (const index of [1, 2, 3, 4, 5].keys()) {
console.log(index);
}
Run Code Online (Sandbox Code Playgroud)
如果要同时访问键和值,可以使用Array.prototype.entries()
与解构:
for (const [index, value] of [1, 2, 3, 4, 5].entries()) {
console.log(index, value);
}
Run Code Online (Sandbox Code Playgroud)
Fel*_*ing 274
Array#entries
如果需要,则返回索引和值:
for (let [index, value] of array.entries()) {
}
Run Code Online (Sandbox Code Playgroud)
chr*_*ris 21
在这个华丽的新本土功能的世界里,我们有时会忘记基础知识.
for (let i = 0; i < arr.length; i++) {
console.log('index:', i, 'element:', arr[i]);
}
Run Code Online (Sandbox Code Playgroud)
干净,高效,你仍然可以break
循环.奖金!您也可以从最后开始,然后向后退i--
!
另一种方法可以使用Array.prototype.forEach()
as
Array.from({
length: 5
}, () => Math.floor(Math.random() * 5)).forEach((val, index) => {
console.log(val, index)
})
Run Code Online (Sandbox Code Playgroud)
You can also handle index yourself if You need the index, it will not work if You need the key.
let i = 0;
for (const item of iterableItems) {
// do something with index
console.log(i);
i++;
}
Run Code Online (Sandbox Code Playgroud)
在for..of
循环中,我们可以通过array.entries()
. array.entries
返回一个新的数组迭代器对象。迭代器对象当时知道如何从可迭代对象访问项目,同时跟踪其在该序列中的当前位置。
当在next()
迭代器上调用该方法时,会生成键值对。在这些键值对中,数组索引是键,数组项是值。
let arr = ['a', 'b', 'c'];
let iterator = arr.entries();
console.log(iterator.next().value); // [0, 'a']
console.log(iterator.next().value); // [1, 'b']
Run Code Online (Sandbox Code Playgroud)
甲for..of
环是基本上消耗可迭代,并通过所有的元素(使用罩下一个迭代)环路的构建体。我们可以array.entries()
通过以下方式将其与此结合:
array = ['a', 'b', 'c'];
for (let indexValue of array.entries()) {
console.log(indexValue);
}
// we can use array destructuring to conveniently
// store the index and value in variables
for (let [index, value] of array.entries()) {
console.log(index, value);
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
123312 次 |
最近记录: |