11.1?不要使用 iterators。使用高階函數(shù)例如?map()
?和?reduce()
?替代?for-of
。
為什么?這加強了我們不變的規(guī)則。處理純函數(shù)的回調(diào)值更易讀,這比它帶來的副作用更重要。
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?現(xiàn)在還不要使用 generators。
為什么?因為它們現(xiàn)在還沒法很好地編譯到 ES5。
更多建議: