扩展原生Number

今天看你不知道的js 第三章有个比较有意思的方法,特记录一下。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
if (!Number.prototype[Symbol.iterator]) {
Object.defineProperty(
Number.prototype,
Symbol.iterator,
{
writable: true,
configurable: true,
enumerable: false,
value: function iterator(){
var i, inc, done = false, top = +this;

// iterate positively or negatively?
inc = 1 * (top < 0 ? -1 : 1);

return {
// make the iterator itself an iterable!
[Symbol.iterator](){ return this; },

next() {
if (!done) {
// initial iteration always 0
if (i == null) {
i = 0;
}
// iterating positively
else if (top >= 0) {
i = Math.min(top,i + inc);
}
// iterating negatively
else {
i = Math.max(top,i + inc);
}

// done after this iteration?
if (i == top) done = true;

return { value: i, done: false };
}
else {
return { done: true };
}
}
};
}
}
);
}

用法

1
2
3
4
5
6
for (var i of 3) {
console.log( i );
}
// 0 1 2 3

[...-3]; // [0,-1,-2,-3]