const a = ["a", "b", "c"]; for (let index = 0; index < a.length; ++index) { const element = a[index]; console.log(element); }
简单的for循环是最传统的方式,灵活性高,可以控制循环的起始、结束和步长。
4. 正确使用for-in
1 2 3 4 5 6 7 8 9 10
const a = []; a[0] = "a"; a[10] = "b"; a[10000] = "c"; for (const name in a) { if (Object.hasOwn(a, name) && /^0$|^[1-9]\d*$/.test(name) && name <= 4294967294) { const element = a[name]; console.log(element); } }
for-in主要用于遍历对象的可枚举属性,在数组上使用时需要添加一些检查来确保只处理数组元素。
5. 显式使用迭代器(ES2015+)
1 2 3 4 5 6 7
const a = ["a", "b", "c"]; const it = a.values(); let entry; while (!(entry = it.next()).done) { const element = entry.value; console.log(element); }
显式使用迭代器可以更精细地控制迭代过程。
对于类数组对象
使用for-of:只要对象提供了迭代器,就可以使用for-of循环。
1 2 3 4
const divs = document.querySelectorAll("div"); for (const div of divs) { div.textContent = Math.random(); }