Iterators and Generators
11.1 不要使用 iterators。使用高阶函数替代循环,如for-in
或者for-of
eslint: no-iterator no-restricted-syntax
为什么?这样能维持我们不变的规则。处理纯函数的返回值比副作用更好理解 使用
map()
/every()
/filter()
/find()
/findIndex()
/reduce()
/some()
/...
来迭代数组,Object.keys()
/Object.values()
/object.entries()
生成数组,以便可以迭代对象
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;
// bad
const increasedByOne = [];
for (let i = 0; i < numbers.length; i++) {
increasedByOne.push(numbers[i] + 1);
}
// good
const increasedByOne = [];
numbers.forEach((num) => {
increasedByOne.push(num + 1);
});
// best (keeping it functional)
const increasedByOne = numbers.map(num => num + 1);
11.2 现在还不要使用 generators
为什么?因为它们现在还没法很好地编译到 ES5。 (译者注:目前 Chrome 和 Node.js 的稳定版本都已支持 generators)
11.3 如果你确实需要使用generators,或者不需要我们的建议,确保generators函数签名分隔正确
eslint: generator-start-spacing
为什么?
function
和*
是相同等级的关键字-*
不是用来改变function
的,function*
是一个独立的结构,和function
没有关系
// bad
function * foo() {
// ...
}
// bad
const bar = function * () {
// ...
};
// bad
const baz = function *() {
// ...
};
// bad
const quux = function*() {
// ...
};
// bad
function*foo() {
// ...
}
// bad
function *foo() {
// ...
}
// very bad
function
*
foo() {
// ...
}
// very bad
const wat = function
*
() {
// ...
};
// good
function* foo() {
// ...
}
// good
const foo = function* () {
// ...
};