迭代器
for of不支持遍历普通对象,这里的普通对象指的是没有Symbol.iterator属性的对象。
当使用for of去遍历某一个数据结构的时候,首先去找Symbol.iterator,找到了就去遍历,没有找到的话不能遍历
对象的Symbol.iterator属性,指向该对象的默认迭代器方法。
手写一个迭代器
function myIterator(arr) {
let index = 0
let value
return {
next: function () {
return index < arr.length ?
{ value: arr[index++], done: false }
: { value: undefined, done: true }
}
}
}
const arry=["你好","我的","未来","!"]
let myIteratorarr=myIterator(arry)
console.log(myIteratorarr.next());
console.log(myIteratorarr.next());
console.log(myIteratorarr.next());
console.log(myIteratorarr.next());
console.log(myIteratorarr.next());
给对象添加迭代器
<script>
const obj = {
name: "小张",
age:12,
height:111,
// 添加Symbol.iterator标识接口以及iterator实现
[Symbol.iterator]: function() {
let index = 0
let value
return {
next: function () {
return index < arr.length ?
{ value: arr[index++], done: false }
: { value: undefined, done: true }
}
}
}
}
</script>
生成器
<script>
function* helloWorldGenerator() {
yield 'hello';
yield 'world';
return 'ending';
}
var hw = helloWorldGenerator();
console.log(hw.next());
console.log(hw.next());
console.log(hw.next());
</script>
当调用 next
方法时,开始执行,遇到 yield
表达式,就暂停后面的操作,将 yield
后面的表达式的值,作为返回的对象的 value
值,因此第一个 myR.next()
中的 value
值为 8
一定需要 yield 语句吗?
其实在生成器函数中也可以没有yield
表达式,但是生成器的特性还在,那么它就变成了一个单纯的暂缓执行函数,只有在调用该函数的遍历器对象的 next 方法才会执行
<script>
function* hello() {
console.log('现在执行');
}
// 生成遍历器对象
let generator = hello()
setTimeout(() => {
// 开始执行
generator.next()
}, 2000)
</script>
注意
next 传递参数
next 方法可以带一个参数,该参数就会被当作上一个 yield 表达式的返回值。