利用ES6 编写更好的条件语句

  • 使用 Array.includes 来处理多个条件

     请看下面的列子:
     // condition
     function test(fruit) {
       if (fruit == 'apple' || fruit == 'strawberry') {
         console.log('red');
       }
     }
     上面的列子看起来似乎没有什么问题。但是,如果我们还有更多的红色水果呢?是否要用
     更多的 || 操作符来扩展该语句,这时可以利用 Array.includes重写上面的条件语句
     
     function test(fruit) {
       // 条件提取到数组中
       const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries'];
      
       if (redFruits.includes(fruit)) {
         console.log('red');
       }
     }
     将所有的可能性条件提取到一个数组中。这样,可以让代码看起来更整洁
    
  • 减少嵌套,提前使用 return 语句

     扩展前面的示例,在包含另外两个条件:
     1.如果没有提供水果,抛出错误;
     2.接受水果数量参数,如果超过10,则打印出相关信息;
     function test(fruit, quantity) {
       const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries'];
       // 条件 1:fruit 必须有值
       if (fruit) {
         // 条件 2:必须为红色
         if (redFruits.includes(fruit)) {
           console.log('red');
      
           // 条件 3:数量必须大于 10
           if (quantity > 10) {
             console.log('big quantity');
           }
         }
       } else {
         throw new Error('No fruit!');
       }
     }
      
     // 测试结果
     test(null); // 抛出错误:No fruits
     test('apple'); // 打印:red
     test('apple', 20); // 打印:red,big quantity
     
     上面的代码,我们有:
     1.1个 if/elss 语句过滤掉无效条件
     2
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值