zoukankan      html  css  js  c++  java
  • 优雅的敲JS代码的几个原则

    一、条件语句

           1,使用 Array.includes 来处理多重 || 条件         

    // ----- 一般 ------
    
        if (fruit == 'apple' || fruit == 'strawberry' || fruit == 'banana'  ) {
              console.log('red');
        }
    
    //------- 优雅 ------
    
        // 把条件提取到数组中
        const redFruits = ['apple', 'strawberry', 'banana', 'cranberries']; 

    if (redFruits.includes(fruit)) {
    console.log(
    'red');
    }

           

            2,少写嵌套,无效条件尽早返回

    /_ 当发现无效条件时尽早返回 _/
    function test(fruit, quantity) {
      const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries'];
    
      if (!fruit) thrownewError('No fruit!'); // 条件 1:尽早抛出错误
      if (!redFruits.includes(fruit)) return; // 条件 2:当 fruit 不是红色的时候,直接返回
      console.log('red');
    
      // 条件 3:必须是大量存在
      if (quantity > 10) {
        console.log('big quantity');
      }
    }

         

          3,使用函数默认参数和解构

    // -------   默认参数  一般   -------
    
    function test(fruit, quantity) {
        if (!fruit) return;
        const q = quantity || 1; // 如果没有提供 quantity,默认为 1
        console.log(`We have ${q}${fruit}!`);
    }
    
    // -------   默认参数  优雅   -------
    
    function test(fruit, quantity = 1) { // 如果没有提供 quantity,默认为 1
        if (!fruit) return;
        console.log(`We have ${quantity}${fruit}!`);
    }
    
    // -------   解构  一般   -------
    
     function test(fruit) { 
        // 如果有值,则打印出来
        if (fruit && fruit.name)  {
          console.log (fruit.name);
        } else {
          console.log('unknown');
        }
    }
    
    // -------   解构  优雅   -------
    
      // 解构 —— 只得到 name 属性
      // 默认参数为空对象 {}
      function test({name} = {}) {
        console.log (name || 'unknown');
      }

         

          4,相较于 switch,Map / Object 也许是更好的选择

    //------   switch   一般 ---------
    
    function test(color) {
      // 使用 switch case 来找到对应颜色的水果
      switch (color) {
        case 'red':
          return ['apple', 'strawberry'];
        case 'yellow':
          return ['banana', 'pineapple'];
        case 'purple':
          return ['grape', 'plum'];
        default:
          return [];
      }
    }
    
    // -----  Object   优雅 -----
    
        // 使用对象字面量来找到对应颜色的水果
        const fruitColor = {
            red: ['apple', 'strawberry'],
            yellow: ['banana', 'pineapple'],
            purple: ['grape', 'plum']
         };
        function test(color) {
          return fruitColor[color] || [];
        }
    
    // -----  Map   优雅 -----
    
      // 使用 Map 来找到对应颜色的水果
      const fruitColor = newMap()
          .set('red', ['apple', 'strawberry'])
          .set('yellow', ['banana', 'pineapple'])
          .set('purple', ['grape', 'plum']);
      function test(color) {
        return fruitColor.get(color) || [];
      }
    
    // -----  filter  优雅 -----
    
    const fruits = [
        { name: 'apple', color: 'red' }, 
        { name: 'strawberry', color: 'red' }, 
        { name: 'banana', color: 'yellow' }, 
        { name: 'pineapple', color: 'yellow' }, 
        { name: 'grape', color: 'purple' }, 
        { name: 'plum', color: 'purple' }
    ];
    function test(color) {
      // 使用 Array filter 来找到对应颜色的水果
      return fruits.filter(f => f.color == color);
    }

          5,使用 Array.every 和 Array.some 来处理全部/部分满足条件

    // -------   直接优雅 --------
    const fruits = [
        { name: 'apple', color: 'red' },
        { name: 'banana', color: 'yellow' },
        { name: 'grape', color: 'purple' }
      ];
    function test() {
      // 条件:(简短形式)所有的水果都必须是红色
      const isAllRed = fruits.every(f => f.color == 'red');
      
      // 条件:至少一个水果是红色的
      const isAnyRed = fruits.some(f => f.color == 'red');
      console.log(isAllRed); // false
    }
  • 相关阅读:
    webpack : 无法加载文件 D: odejs ode_globalwebpack.ps1,因为在此系统上禁止运行脚本。
    TypeError: __WEBPACK_IMPORTED_MODULE_0_react___default.a.createContext is not a function报错处理
    React中import的用法
    antd-react-mobile(踩坑记录)
    [转][C#]BarCodeToHTML
    [转][C#]Environment 类
    [转][easyui]右键菜单
    [转][C#]Web.config 相关配置
    [转]模拟键盘输入
    python3 的 zip
  • 原文地址:https://www.cnblogs.com/smlp/p/9812013.html
Copyright © 2011-2022 走看看