• javaScript-条件语句优化


    1、多重判断时使用 Array.includes

    test = (fruit: string) => {
        if (fruit == 'apple' || fruit == 'strawberry'....) {
          console.log('apple or strawberry');
        }
      }
    test = (fruit: string) => {
        const fruits = ['strawberry','apple'];
        if (fruits.includes(fruit)) {
          console.log('apple or strawberry');
        }
      }

     2、使用默认参数和解构

    在JavaScript中我们总是需要检查 null / undefined的值和指定默认值:

    test = (fruit: string, quantity?: any) => {
        if (!fruit) {
          return;
        }
        console.log(quantity || 0)
      }

    我们可以通过声明 默认函数参数

    test = (fruit: string, quantity: any = 20) => {
        if (!fruit) {
          return;
        }
        console.log(quantity)
      }
    test = (fruit?: any) => {
        if (fruit && fruit.name) {
          console.log(fruit.name)
        } else {
          console.log('unknown')
        }
      }

    通过默认参数以及解构从而避免判断条件 fruit && fruit.name

    test = ({ name }: any = {}) => {
        console.log(name || 'name unknown')
      }

    我们也需要声明空对象 {} 作为默认值。如果我们不这么做,当执行 test(undefined) 时,你将得到一个无法对 undefined 或 null 解构的的错误。因为在 undefined 中没有 name 属性。

    也可以使用lodash的_.get()方法减少对null的检查

    3、倾向于对象遍历而不是Switch语句

    test = (color: string) => {
        switch (color) {
          case 'red':
            return ['apple', 'strawberry'];
          case 'yellow':
            return ['banana', 'pineapple'];
          case 'purple':
            return ['grape', 'plum'];
          default:
            return [];
        }
      }

    在这种场景,我们可以用对象遍历实现相同的结果,语法看起来更简洁:

    test = (color: string) => {
        const fruitColor = {
          red: ['apple', 'strawberry'],
          yellow: ['banana', 'pineapple'],
          purple: ['grape', 'plum']
        };
        return fruitColor[color] ||[]
      }

    4、对 所有/部分 判断使用Array.every & Array.some

    利用 JavaScript Array 的内置方法来减少代码行数。看下面的代码,我们想要检查是否所有水果都是红色:

    const fruits = [
          { name: 'apple', color: 'red' },
          { name: 'banana', color: 'yellow' },
          { name: 'grape', color: 'purple' }
        ];

    test = (fruits: any = []) => { let isAllRed: boolean = true; // 条件:所有水果都是红色

      for (let f of fruits) { if (!isAllRed) break; isAllRed = (f.color == 'red'); } }
    test9 = (fruits: any = []) => {
        console.log(fruits.every((item: any) => item.color === 'red'))
      }
    
    test10 = (fruits: any = []) => {
        console.log(fruits.some((item: any) => item.color === 'red'))
      }

    5、更少的嵌套,尽早 Return

    例子: 

    • 如果没有传入参数 fruit,抛出错误

    • 接受 quantity 参数,并且在 quantity 大于 10 时打印出来

    test = (fruit: any, quantity: any) => {
        const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries'];
        // 条件 1: fruit 必须有值
        if (fruit) {
          // 条件 2: 必须是red的
          if (redFruits.includes(fruit)) {
            console.log('red');
    
            // 条件 3: quantity大于10
            if (quantity > 10) {
              console.log('big quantity');
            }
          }
        } else {
          throw new Error('No fruit!');
        }
      }

    当发现无效语句时,尽早Return

    test = (fruit: any, quantity: any) => {
        const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries'];
        // 条件 1: fruit 必须有值
        if (!fruit) {
          throw new Error('No fruit!');
          return;
        } 
        // 条件 2: 必须是red的
        if (redFruits.includes(fruit)) {
          console.log('red');
    
          // 条件 3: quantity大于10
          if (quantity > 10) {
            console.log('big quantity');
          }
        }
      }
  • 相关阅读:
    李开复:如何设计你的2015年度计划(转)
    深入浅出 Java 多线程(转)
    maven常见问题汇总 专题
    Introduction to the Build Lifecycle
    具体解释EBS接口开发之WIP模块接口
    Shell脚本编程具体解释
    [数字图像处理]图像去噪初步(1)--均值滤波器
    hdu-4302-Holedox Eating-线段树-单点更新,有策略的单点查询
    响应式设计:理解设备像素,CSS像素和屏幕分辨率
    #define
  • 原文地址:https://www.cnblogs.com/Nyan-Workflow-FC/p/10457526.html
Copyright © 2020-2023  润新知