zoukankan      html  css  js  c++  java
  • JS 优化条件语句的5个技巧

    前言

    在使用 JavaScript 的时候,有时我们会处理大量条件语句,这里有5个技巧帮助我们编写更简洁的条件语句。

    一、对多个条件使用 Array.includes

    例子:

    function condition(fruit) {
      if (fruit == 'apple' || fruit == 'banana') {
        console.log(fruit);
      }
    }

    上面的例子看起来不错,但如果有更多水果需要判断呢,比如桃子、草莓、橙子等等,我们要用更多的 || 来扩展这个表述吗?

    我们可以使用 Array.includes 重写上面的条件

    function condition(fruit){
        const allFruit = ['apple','banana','peach','Strawberry','orange'];
        if(allFruit.includes(fruit)){
            console.log(fruit)
        }
    }

    这样做之后,代码看起来更简洁。

    二、更少的嵌套,尽早返回

    例子:

    // 尽早返回不存在的条件
    
    function condition(fruit, quantity) {
        const allFruits = ['apple','banana','peach','Strawberry','orange'];
     
        if (!fruit) throw new Error('No fruit!');
    
        if (allFruits.includes(fruit)) { 
            console.log(fruit); 
    
            if (quantity > 10) { 
                console.log(quantity); 
            }
    
        } 
    }     

    通过反转条件和提早返回,我们可以进一步减少嵌套:

    function condition(fruit, quantity) {
        const allFruits = ['apple','banana','peach','Strawberry','orange'];
     
        if (!fruit) throw new Error('No fruit!');
    
        if (!allFruits.includes(fruit)) return ;
    
        console.log(fruit)
    
        if (quantity > 10) { 
            console.log(quantity); 
        }
    }  

    三、使用默认的函数参数和解构

    例子:

    function condition(fruit, quantity) {
      if (!fruit) return;
      const q = quantity || 1; 
    
      console.log(`We have ${q} ${fruit}!`);
    }
    
    condition('banana'); // We have 1 banana!
    condition('apple', 2); // We have 2 apple!

    使用默认参数和解构:

    function condition({name} = {}, quantity = 1) {
      console.log (name || 'unknown');
    }
    
    condition(undefined); // unknown
    condition({ }); // unknown
    condition({ name: 'apple', color: 'red' }); // apple

    四、选择 Map 或对象字面量,而不是 Switch 语句

    例子:

    function condition(color) {
      switch (color) {
        case 'red':
          return ['apple', 'strawberry'];
        case 'yellow':
          return ['banana', 'pineapple'];
        case 'purple':
          return ['grape', 'plum'];
        default:
          return [];
      }
    }
    
    condition(null); // []
    condition('yellow'); // ['banana', 'pineapple']

    上面的代码似乎没有什么问题,但我发现它相当冗长。同样的结果可以通过对象字面量和更简洁的语法来实现:

    对象字面量:

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

    使用 Map 实现相同效果:

    const fruitColor = new Map()
        .set('red', ['apple', 'strawberry'])
        .set('yellow', ['banana', 'pineapple'])
        .set('purple', ['grape', 'plum']);
    
    function condition(color) {
      return fruitColor.get(color) || [];
    }

    使用 Array.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 condition(color) {
     return fruits.filter(f => f.color == color);
    }

    五、所有或部分使用 Array.every & Array.some 的条件 

    例子:

    检查所有水果都为红色:

    const fruits = [
        { name: 'apple', color: 'red' },
        { name: 'banana', color: 'yellow' },
        { name: 'grape', color: 'purple' }
      ];
    
    function condition() {
      let isAllRed = true;
    
      for (let f of fruits) {
        if (!isAllRed) break;
        isAllRed = (f.color == 'red');
      }
    
      console.log(isAllRed); // false
    }

    代码太长了!我们可以用 Array.every 来减少行数:

    const fruits = [
        { name: 'apple', color: 'red' },
        { name: 'banana', color: 'yellow' },
        { name: 'grape', color: 'purple' }
      ];
    
    function test() {
    const isAllRed = fruits.every(f => f.color == 'red'); console.log(isAllRed); // false }

    如果我们想用一行代码来判断任何一个水果是否为红色,我们可以使用 Array.some

    const fruits = [
        { name: 'apple', color: 'red' },
        { name: 'banana', color: 'yellow' },
        { name: 'grape', color: 'purple' }
    ];
    
    function condition() {
    const isAnyRed
    = fruits.some(f => f.color == 'red'); console.log(isAnyRed); // true }
    随笔整理自
      http://blog.jobbole.com/114671/
    感谢博主分享!
  • 相关阅读:
    rabbitmq安装详解
    linux下安装rabbitmq的rpm包问题记录
    在 CentOS 6.4上安装Erlang
    redis配置认证密码(转)
    Redis单台的安装部署及主备、哨兵部署
    查看linux系统版本的命令
    Js 实现ajax
    json的相关操作
    Diango思维图
    服务系统 server端
  • 原文地址:https://www.cnblogs.com/gaosirs/p/10684125.html
Copyright © 2011-2022 走看看