zoukankan      html  css  js  c++  java
  • js条件语句更好的写法

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

    一般写法:

    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');
      }
    }

    2、减少嵌套,提前使用return语句

    一般写法:

    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

    优化写法:

    /* 在发现无效条件时提前 return */
    function test(fruit, quantity) {
      const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries'];
      // 条件 1:提前抛出错误
      if (!fruit) throw new Error('No fruit!');
      // 条件2:必须为红色
      if (redFruits.includes(fruit)) {
        console.log('red');
        // 条件 3:数量必须大于 10
        if (quantity > 10) {
          console.log('big quantity');
        }
      }
    }

    再次优化:

    /* 在发现无效条件时提前 return */
    function test(fruit, quantity) {
      const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries'];
      if (!fruit) throw new Error('No fruit!'); // 条件 1:提前抛出错误
      if (!redFruits.includes(fruit)) return;  // 条件 2:当 fruit 不是红色的时候,提前 return
      console.log('red');
      // 条件 3:必须是大量存在
      if (quantity > 10) {
        console.log('big quantity');
      }
    }

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

    一般写法:

    function test(fruit, quantity) {
      if (!fruit) return;
      const q = quantity || 1; // 如果没有提供 quantity 参数,则默认为 1
      console.log(`We have ${q} ${fruit}!`);
    }
    // 测试结果
    test('banana'); // We have 1 banana!
    test('apple', 2); // We have 2 apple!

    优化写法:

    function test(fruit, quantity = 1) { // i如果没有提供 quantity 参数,则默认为 1
      if (!fruit) return;
      console.log(`We have ${quantity} ${fruit}!`);
    }
    // 测试结果
    test('banana'); // We have 1 banana!
    test('apple', 2); // We have 2 apple!

    4、选择Map/Object字面量,而不是Switch语句

    一般写法:

    function test(color) {
      // 使用 switch case 语句,根据颜色找出对应的水果
      switch (color) {
        case 'red':
          return ['apple', 'strawberry'];
        case 'yellow':
          return ['banana', 'pineapple'];
        case 'purple':
          return ['grape', 'plum'];
        default:
          return [];
      }
    }
    //测试结果
    test(null); // []
    test('yellow'); // ['banana', 'pineapple']

    优化写法:

    // 使用对象字面量,根据颜色找出对应的水果
      const fruitColor = {
        red: ['apple', 'strawberry'],
        yellow: ['banana', 'pineapple'],
        purple: ['grape', 'plum']
      };
    function test(color) {
      return fruitColor[color] || [];
    }

    使用Map来实现:

    // 使用 Map ,根据颜色找出对应的水果
      const fruitColor = new Map()
        .set('red', ['apple', 'strawberry'])
        .set('yellow', ['banana', 'pineapple'])
        .set('purple', ['grape', 'plum']);
    function test(color) {
      return fruitColor.get(color) || [];
    }

    5、使用Array.every和Array.some来处理全部/部分满足条件

    一般写法:

    const fruits = [
        { name: 'apple', color: 'red' },
        { name: 'banana', color: 'yellow' },
        { name: 'grape', color: 'purple' }
      ];
    function test() {
      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 test() {
      // 条件:简短方式,所有的水果都必须是红色
      const isAllRed = fruits.every(f => f.color == 'red');
      console.log(isAllRed); // false
    }
  • 相关阅读:
    操作~拷贝clone()
    属性/css~储存
    属性/css~位置.offset()&offsetParent()&position()&scrollTop()&scrollLeft()
    属性/css~尺寸.height()
    设置,获取,删除cookie方法
    Cookie
    属性/css~css.css()
    Python井字游戏
    Asp.net vNext 学习之路(三)
    使用C#发送Http 请求实现模拟登陆(以博客园为例)
  • 原文地址:https://www.cnblogs.com/chao202426/p/13589679.html
Copyright © 2011-2022 走看看