5. Set 和 Map

1. 数组去重

  1. // 例子 5-1
  2.  
  3. [...new Set(array)]

2. 条件语句的优化

  1. // 例子 5-2
  2. // 根据颜色找出对应的水果
  3.  
  4. // bad
  5. function test(color) {
  6. switch (color) {
  7. case 'red':
  8. return ['apple', 'strawberry'];
  9. case 'yellow':
  10. return ['banana', 'pineapple'];
  11. case 'purple':
  12. return ['grape', 'plum'];
  13. default:
  14. return [];
  15. }
  16. }
  17.  
  18. test('yellow'); // ['banana', 'pineapple']
  1. // good
  2. const fruitColor = {
  3. red: ['apple', 'strawberry'],
  4. yellow: ['banana', 'pineapple'],
  5. purple: ['grape', 'plum']
  6. };
  7.  
  8. function test(color) {
  9. return fruitColor[color] || [];
  10. }
  1. // better
  2. const fruitColor = new Map()
  3. .set('red', ['apple', 'strawberry'])
  4. .set('yellow', ['banana', 'pineapple'])
  5. .set('purple', ['grape', 'plum']);
  6.  
  7. function test(color) {
  8. return fruitColor.get(color) || [];
  9. }