Set and Map

1. deduplication array

        <script type="text/javascript">
            [...new Set(array)]
        </script>

2. Optimization of conditional statements

        <Script type = "text / JavaScript">
             // the color to identify the corresponding fruit 
            // 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) || [];
            }
        </script>

Guess you like

Origin www.cnblogs.com/wangxi01/p/11590125.html