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

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

    // 条件语句
    function test(fruit) {
      if (fruit == 'apple' || fruit == 'strawberry') {
        console.log('red');
      }
    }
    function test(fruit) {
      // 把条件提取到数组中
      const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries'];
    
      if (redFruits.includes(fruit)) {
        console.log('red');
      }
    }

    2. 少写嵌套,尽早返回

    function test(fruit, quantity) {
      const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries'];
    
      // 条件 1:fruit 必须有值
      if (fruit) {
        // 条件 2:必须为红色
        if (redFruits.includes(fruit)) {
          console.log('red');
    
          // 条件 3:必须是大量存在
          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
    /_ 当发现无效条件时尽早返回 _/
    
    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 不是红色的时候,直接返回
    
      console.log('red');
    
      // 条件 3:必须是大量存在
      if (quantity > 10) {
        console.log('big quantity');
      }
    }

    3. 相较于 switch,Map / Object 也许是更好的选择

    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) || [];
    }

    map() 方法返回一个由原数组中的每个元素调用一个指定方法后的返回值组成的新数组。

     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 test(color) {
      // 使用 Array filter 来找到对应颜色的水果
    
      return fruits.filter(f => f.color == color);
    }

    4. 使用 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
    }
    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 isAnyRed = fruits.some(f => f.color == 'red');
    
      console.log(isAnyRed); // true
    }

    本文参考掘金大佬Hopsken!

    map() 方法返回一个由原数组中的每个元素调用一个指定方法后的返回值组成的新数组。

  • 相关阅读:
    再谈TextField
    IOS-TextField知多少
    leftBarButtonItems
    LeftBarButtonItems,定制导航栏返回按钮
    Apple Mach-O Linker (id) Error "_OBJC_CLASS...错误解决办法 Apple Mach-O Linker (id) Error "_OBJC_CLASS...错误解决办法
    Unrecognized Selector Sent to Instance问题之诱敌深入关门打狗解决办法
    UNRECOGNIZED SELECTOR SENT TO INSTANCE 问题快速定位的方法
    Present ViewController,模态详解
    UILABEL AUTOLAYOUT自动换行 版本区别
    iOS自动布局解决警告Automatic Preferred Max Layout Width is not available on iOS versions prior to 8.0
  • 原文地址:https://www.cnblogs.com/guors/p/jscode.html
Copyright © 2011-2022 走看看