可迭代对象
- Array
[10, 20, 30]
- String
"boo"
- TypedArrayc
new Uint8Array([0x00, 0xff])
- Map
new Map([["a", 1], ["b", 2], ["c", 3]])
- Set
new Set([1, 1, 2, 2, 3, 3])
- arguments
(function() {for (let arg of arguments) console.log(arg)})(1, 2, 3)
- Nodelist
document.querySelectorAll("article > p")
( 浏览器需支持 Nodelist [Symbol.iterator] )
[注意]
document.getElementById 返回一个实时的 NodeList
document.querySelectorAll 返回一个静态的 NodeList
for...of
for...of语句在可迭代对象上创建一个迭代循环,调用自定义迭代钩子,并为每个不同属性的值执行语句。
for...of还可以迭代生成器,生成器不应该重用。
for...of与for...in的区别
for...in 语句以原始插入顺序迭代对象的可枚举属性。
for...of 语句遍历可迭代对象定义要迭代的数据。
Object.prototype.objCustom = function() {}
Array.prototype.arrCustom = function() {}
let iterable = [3, 5, 7]
iterable.foo = 'hello'
for (let i in iterable){
console.log(i) // logs 0, 1, 2, "foo", "arrCustom", "objCustom"
if (iterable.hasOwnProperty(i))
console.log(i) // logs 0, 1, 2, "foo"
}
for (let i of iterable)
console.log(i) // logs 3, 5, 7
终止迭代
break,return throw
[注意] Array.forEach 不能 break
Range(n) in JS
https://stackoverflow.com/que...
Numbers
[...Array(5).keys()];
=> [0, 1, 2, 3, 4]
Character iteration
String.fromCharCode(
...[...Array('D'.charCodeAt(0) - 'A'.charCodeAt(0) + 1).keys()]
.map(i => i + 'A'.charCodeAt(0)));
=> "ABCD"
Iteration
for (const x of Array(5).keys()) {
console.log(x, String.fromCharCode('A'.charCodeAt(0) + x));
}
=> 0,"A" 1,"B" 2,"C" 3,"D" 4,"E"
As functions
function range(size, startAt = 0) {
return [...Array(size).keys()].map(i => i + startAt);
}
function characterRange(startChar, endChar) {
return String.fromCharCode(...range(endChar.charCodeAt(0) -
startChar.charCodeAt(0), startChar.charCodeAt(0)))
}
As typed functions
function range(size:number, startAt:number = 0):ReadonlyArray {
return [...Array(size).keys()].map(i => i + startAt);
}
function characterRange(startChar:string, endChar:string):ReadonlyArray {
return String.fromCharCode(...range(endChar.charCodeAt(0) -
startChar.charCodeAt(0), startChar.charCodeAt(0)))
}
lodash.js _.range() function
_.range(10);
=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
_.range(1, 11);
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
_.range(0, 30, 5);
=> [0, 5, 10, 15, 20, 25]
_.range(0, -10, -1);
=> [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
String.fromCharCode(..._.range('A'.charCodeAt(0), 'D'.charCodeAt(0) + 1));
=> "ABCD"
Old non es6 browsers without a library:
Array.apply(null, Array(5)).map(function (_, i) {return i;});
=> [0, 1, 2, 3, 4]
console.log([...Array(5).keys()]);