11. Iterators & Generators

2018-02-24 16:11 更新
  • 11.1 不要使用 iterators。使用高阶函数例如 map() 和 reduce() 替代 for-of

    为什么?这加强了我们不变的规则。处理纯函数的回调值更易读,这比它带来的副作用更重要。

      const numbers = [1, 2, 3, 4, 5];
    
      // bad
      let sum = 0;
      for (let num of numbers) {
        sum += num;
      }
    
      sum === 15;
    
      // good
      let sum = 0;
      numbers.forEach((num) => sum += num);
      sum === 15;
    
      // best (use the functional force)
      const sum = numbers.reduce((total, num) => total + num, 0);
      sum === 15;
  • 11.2 现在还不要使用 generators。

    为什么?因为它们现在还没法很好地编译到 ES5。

以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号