ES6 generator Symbol yield
Symbol 独一无二的值
const s1 = Symbol('a')
const s2 = Symbol('a')
console.log(s1 === s2) // false
console.log(typeof s1) // 'symbol'
let o = {
a: 90,
}
let symbol = Symbol()
o[symbol] = 100
console.log(o)//{a: 90, Symbol(): 100}
普通函数一旦执行 函数体从上往下依次执行
function f() {
console.log(1)//1
console.log(2)//2
console.log(3)//3
}
f()
生成器函数(generator)-生成迭代器(Iterator)的函数,配合yield关键字来控制代码执行流程
function* go(str) {
console.log(1)//1
let a = yield str
console.log(2)//2
let b = yield a
console.log(3)//3
return b
}
const it = go('hehe')
console.log(it)
const r1 = it.next(1)
console.log(r1)//{value:'hehe',done: false}
const r2 = it.next(2)
console.log(r2)//{value: 2, done: false}
const r3 = it.next(3)
console.log(r3)//{value: 3, done: true}
function* test(num) {
let x = 3 * (yield num + 1)
let y = yield x / 3
return x + y + num
}
let n = test(3)
console.log(n.next()) // {value: 4, done: false}
console.log(n.next(5)) // {value: 5, done: false}
console.log(n.next(8)) // {value: 26, done: true}
自己模拟生成器函数
function* buy(books) {
for (let i = 0; i < books.length; i++) {
yield books[i]
}
}
const it = buy(['js', 'vue'])
console.log(it.next()) //{value: 'js', done: false}
console.log(it.next()) // { value: 'vue', done:true}
console.log(it.next())//{value: undefined, done: true}
for-of遍历迭代器
function* demo() {
yield 1
yield 2
yield 3
return 4
}
const it = demo()
for (let k of it) {
console.log(k)
}
yield是ES6的新关键字,使生成器函数执行暂停,yield关键字后面的表达式的值返回给生成器的调用者。它可以被认为是一个基于生成器的版本的return关键字。
yield关键字实际返回一个IteratorResult(迭代器)对象,它有两个属性,value和done,分别代表返回值和是否完成。
yield无法单独工作,需要配合generator(生成器)的其他函数,如next,懒汉式操作,展现强大的主动控制特性。
function* test() {
yield 'a'
yield 'b'
}
function* test1() {
yield 'x'
// yield* test()
// for (let k of test()) {
// console.log(k)
// }
yield 'y'
}
for (let v of test1()) {
console.log(v)
}
function* Person() {
yield (this.name = 'zs')
yield (this.age = 18)
}
let person = {}
let obj = Person.bind(person)()
console.log(obj.next())//{value: 'zs', done: false}
console.log(obj.next())//{value: 18, done: false}
console.log(person)//{name: 'zs', age: 18}
generator应用
const oImg = document.querySelector('img')
let flag = true // 第一张
function* change() {
while (true) {
yield (oImg.src = './images/2.jpg')
yield (oImg.src = './images/1.jpg')
}
}
const it = change()
document.querySelector('.btn').addEventListener('click', function () {
it.next()
})