let iterable = [10, 20, 30]; for (let value of iterable) { console.log(value); } // 10 // 20 // 30
循环一个字符串 String
1 2 3 4 5 6 7 8
let iterable = "boo"; for (let value of iterable) { console.log(value); } // "b" // "o" // "o"
循环一个类型化的数组 TypedArray
1 2 3 4 5 6 7
let iterable = newUint8Array([0x00, 0xff]); for (let value of iterable) { console.log(value); } // 0 // 255
循环一个 Map
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
let iterable = newMap([["a", 1], ["b", 2], ["c", 3]]); for (let [key, value] of iterable) { console.log(value); } // 1 // 2 // 3 for (let entry of iterable) { console.log(entry); } // [a, 1] // [b, 2] // [c, 3]
循环一个 Set
1 2 3 4 5 6 7 8
let iterable = newSet([1, 1, 2, 2, 3, 3]); for (let value of iterable) { console.log(value); } // 1 // 2 // 3
循环一个 DOM 集合
1 2 3 4 5 6 7
// Note: This will only work in platforms that have // implemented NodeList.prototype[Symbol.iterator] let articleParagraphs = document.querySelectorAll("article > p"); for (let paragraph of articleParagraphs) { paragraph.classList.add("read"); }
循环一个生成器 Generators
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
function* fibonacci() { // a generator function let [prev, curr] = [0, 1]; while (true) { [prev, curr] = [curr, prev + curr]; yield curr; } } for (let n of fibonacci()) { console.log(n); // truncate the sequence at 1000 if (n >= 1000) { break; } }
<span tabindex="4">This wouldn't normally receive focus</span> has (4) largest value. Next tab will give focus to the rest of tabnavigable elements in code source order.