复制代码
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
48
49
50
51
52
53
54
55
56
57
58一、for...of为什么不能遍历对象 因为对象的构造函数中没有Symbol类型的属性 Symbol.iterator */ console.log(Array.prototype); console.log(String.prototype); console.log(Set.prototype); console.log(Map.prototype); console.log(Object.prototype); /* 二、iterator遍历器(迭代器)原理:当可遍历对象被for...of遍历的时候,[Symbol.iterator]()就会被调用,返回一个iterator对象。 */ var arr = [10, 20, 30, 40] console.log(arr); console.log(arr[Symbol.iterator]()); var ite = arr[Symbol.iterator]() /* 三、for...of遍历的原理: 当可遍历对象被for...of遍历的时候,[Symbol.iterator]()就会被调用,返回一个iterator对象, iterator里面的next()方法一直被调用,返回一个对象,里面有value,done属性, 直到done属性的属性值变成true,结束循环。 */ console.log(ite.next());//{value: 10, done: false} console.log(ite.next());//{value: 20, done: false} console.log(ite.next());//{value: 30, done: false} console.log(ite.next());//{value: 40, done: false} console.log(ite.next());//{value: undefined, done: true} /* 四、自定义迭代器 */ var obj = { 1: '我是1', 2: '我是2', 3: '我是3', [Symbol.iterator]() { let index = 0; return { next: () => { index++ let value = this[index] let done = index > 3 return { value, done } } } } } // console.log(obj[2]); for (let value of obj) { console.log(value); } /* 我是1 我是2 我是3 */
最后
以上就是糟糕秀发最近收集整理的关于iterator遍历器(迭代器)的全部内容,更多相关iterator遍历器(迭代器)内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复