5. Set 和 Map
1. 数组去重
- // 例子 5-1
-
- [...new Set(array)]
2. 条件语句的优化
- // 例子 5-2
- // 根据颜色找出对应的水果
-
- // bad
- function test(color) {
- switch (color) {
- case 'red':
- return ['apple', 'strawberry'];
- case 'yellow':
- return ['banana', 'pineapple'];
- case 'purple':
- return ['grape', 'plum'];
- default:
- return [];
- }
- }
-
- test('yellow'); // ['banana', 'pineapple']
- // good
- const fruitColor = {
- red: ['apple', 'strawberry'],
- yellow: ['banana', 'pineapple'],
- purple: ['grape', 'plum']
- };
-
- function test(color) {
- return fruitColor[color] || [];
- }
- // better
- const fruitColor = new Map()
- .set('red', ['apple', 'strawberry'])
- .set('yellow', ['banana', 'pineapple'])
- .set('purple', ['grape', 'plum']);
-
- function test(color) {
- return fruitColor.get(color) || [];
- }