if (redFruits.includes(fruit)) { console.log('red'); } }
2. 更少的嵌套,尽早返回
让我们扩展前面的示例,以包含另外两个条件:
如果没有提供水果(名称),抛出错误。
如果(红色水果)数量超过 10 个,接受并打印。
看看上面的代码,我们有:
1组过滤无效条件的 if/else 语句
3层的 if 嵌套语句(条件 1、2、3)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
<!--当发现无效条件时,提前返回--> function getFruitColor(fruit, quantity) { const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries']; // condition 1: throw error early if (!fruit) throw new Error('No fruit!'); // condition 2: must be red if (redFruits.includes(fruit)) { console.log('red'); // condition 3: must be big quantity if (quantity > 10) { console.log('big quantity'); } } }
通过反转条件和提早返回,我们可以进一步减少嵌套。看看下面的条件 1、2,我们是怎么做的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
function getFruitColor(fruit, quantity) { const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries']; // condition 1: throw error early if (!fruit) throw new Error('No fruit!'); // condition 2: stop when fruit is not red if (!redFruits.includes(fruit)) return; console.log('red'); // condition 3: must be big quantity if (quantity > 10) { console.log('big quantity'); } }
// Include lodash library, you will get _ function test(fruit) { console.log(__.get(fruit, 'name', 'unknown'); // get property name, if not available, assign default value 'unknown' } //test results test(undefined); // unknown test({ }); // unknown test({ name: 'apple', color: 'red' }); // apple
function test(color) { // use switch case to find fruits in color switch (color) { case 'red': return ['apple', 'strawberry']; case 'yellow': return ['banana', 'pineapple']; case 'purple': return ['grape', 'plum']; default: return []; } } //test results test(null); // [] test('yellow'); // ['banana', 'pineapple']
我们发现虽然可以实现但代码相当冗长。同样的结果可以通过对象字面量和更简洁的语法来实现:
1 2 3 4 5 6 7 8 9 10
// use object literal to find fruits in color const fruitColor = { red: ['apple', 'strawberry'], yellow: ['banana', 'pineapple'], purple: ['grape', 'plum'] }; function test(color) { return fruitColor[color] || []; }
或者,可以使用 Map 来实现相同的结果:
1 2 3 4 5 6 7 8 9
// use Map to find fruits in color const fruitColor = new Map() .set('red', ['apple', 'strawberry']) .set('yellow', ['banana', 'pineapple']) .set('purple', ['grape', 'plum']); function test(color) { return fruitColor.get(color) || []; }