10
0

27_Generator.html 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>Document</title>
  7. </head>
  8. <body>
  9. <script>
  10. // 使用 Generator 可讲内部代码分段执行 执行yield停止, 通过next()控制继续往下执行
  11. // function* foo(){
  12. // console.log(1);
  13. // console.log("hello");
  14. // yield;
  15. // console.log(2);
  16. // yield;
  17. // console.log(3);
  18. // }
  19. // let foo1 = foo();
  20. // foo1.next();
  21. // foo1.next();
  22. // foo1.next();
  23. // next 方法有返回值 分别是当前yield语句后边的结果 第二个值为是否结束
  24. // newt也可以传参数 参数给到上一个yield
  25. // function* foo(){
  26. // console.log(1)
  27. // let x = yield "a";
  28. // console.log(x)
  29. // console.log(2);
  30. // yield 2;
  31. // console.log(3);
  32. // return "你好";
  33. // }
  34. // let foo1 = foo();
  35. // console.log(foo1.next());
  36. // console.log(foo1.next("hello"));
  37. // console.log(foo1.next());
  38. function* foo(x) {
  39. var y = 2 * (yield (x + 1));
  40. console.log(y);
  41. var z = yield (y / 3);
  42. return (x + y + z);
  43. }
  44. let foo2 = foo(1);
  45. console.log(foo2.next());
  46. console.log(foo2.next(3));
  47. console.log(foo2.next(1));
  48. </script>
  49. </body>
  50. </html>