zoukankan      html  css  js  c++  java
  • JS-条件语句5准则

    准则:

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

    2.更少的嵌套,尽早 return

    3.使用默认参数和解构

    4.倾向于遍历对象而不是 Switch 语句

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

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

    例子:查询水果是什么

    function test(value) {
    
      if (value== '苹果' || value== '香蕉') {
        console.log('输入的是水果'+value);
      }
    }

    当有很多时怎么办呢?,使用Array.includes (Array.includes)重写条件语句

    function test(value) {
    
      const datas = ['苹果','香蕉','火龙果',芒果,];
    
      if (datas.includes(value)){
    
        console.log('输入的是水果'+value);
    
      }
    
    }

    2.更少的嵌套,尽早 Return

     例子:判断值为空抛出错误为真继续进行

    function test(value) {
           
          const datas = ['苹果','香蕉','火龙果',芒果,];
      
          if (value) {
           if (datas.includes(value)){
            console.log('输入的是水果'+value);
            }
        }else{
           console.log("输入内容有误,不是我这的水果");   
              return false
        }
    
    }

    改进方法:去掉一层嵌套 判断为假先return

    function test(value) {
          if (!value) {
               console.log("输入内容有误,不是我这的水果");   
               return false
          }  
          
          const datas = ['苹果','香蕉','火龙果',芒果,];
      
          if (datas.includes(value)){
    
            console.log('输入的是水果'+value);
    
         }
    
    }

    3.使用默认参数和解构

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

    function test(fruit, quantity) {
      if (!fruit) return;    
      // 如果 quantity 参数没有传入,设置默认值为 1
      const q = quantity || 1; 
    
      console.log(`We have ${q} ${fruit}!`);
    }
    
    //test results
    test('banana'); // We have 1 banana!
    test('apple', 2); // We have 2 apple!

    改进为更直观的形式:

    function test(fruit, quantity = 1) {
      // 如果 quantity 参数没有传入,设置默认值为 1
      if (!fruit) return;
      console.log(`We have ${quantity} ${fruit}!`);
    }
    
    //test results
    test('banana'); // We have 1 banana!
    test('apple', 2); // We have 2 apple!
  • 相关阅读:
    深入理解加密、解密、数字签名和数字证书
    支付网关的设计
    spring boot Rabbitmq集成,延时消息队列实现
    五一之起一台服务器玩玩-u盘安装centos
    shell初识
    用户身份切换之初窥企业远程用户没root还有root权限
    man帮助文档打印
    开源镜像软件下载网址{转载}
    bash shell第一课
    jQuery常用ajax操作
  • 原文地址:https://www.cnblogs.com/yangchin9/p/10475677.html
Copyright © 2011-2022 走看看