zoukankan      html  css  js  c++  java
  • 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');
          }
        }
      }
  • 相关阅读:
    What's the most secure desktop operating system?
    合肥一中在校学生丁雯琪(中美班)被麻省理工学院(MIT)录取
    Classic Computer Science 1980s-1990s
    HOWTO do Linux kernel development
    选择器zuoye
    HTML+css 小组件
    弹性盒子
    CSS3 学习笔记(动画 多媒体查询)
    CSS3 学习笔记(边框 背景 字体 图片 旋转等)
    学习笔记css3
  • 原文地址:https://www.cnblogs.com/Nyan-Workflow-FC/p/10457526.html
Copyright © 2011-2022 走看看