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!
原文地址:https://www.cnblogs.com/yangchin9/p/10475677.html