1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950 |
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta http-equiv="X-UA-Compatible" content="IE=edge">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Document</title>
- </head>
- <body>
- <script>
- /**
- * 是一种特殊的函数
- * 可以异步编程
- * yield : 函数代码分隔符
- */
- //声明方式
- function* gen(){
- console.log('hhh')
- yield 'hello'
- console.log('111')
- yield 'hi'
- console.log('222')
- yield 'youxi'
- console.log('333')
- }
- let iterator = gen()
- //console.log(iterator) //输出迭代器对象
- iterator.next() // hhh
- iterator.next() // 111
- iterator.next() // 222
- iterator.next() // 333
- //可以使用for of遍历
- for(let v of gen()){
- console.log(v) // 每一个yield后的表达式
- }
- //参数传递
- function* gen1(arg){
- console.log(arg)
- let bbb = yield 'hello'
- console.log(bbb)
- yield 'hi'
- }
- let iterator1 = gen1('testwww')
- console.log(iterator1.next());
- console.log(iterator1.next('bbb')); //next传入参数,会把它当作前一个yield返回结果
- </script>
- </body>
- </html>
|