Tip:Write Better Conditionals in JavaScript

条件语句
1、if……else……
2、 if……else if……
3、switch……case……

文章来源于https://scotch.io/bar-talk/5-tips-to-write-better-conditionals-in-javascript

1. 对多个条件使用Array.includes

// condition
function test(char) {
  if (char == 'a' || fruit == 'b') {
    console.log('true');
  }
}

当出现多个“||”时,那该如何?

function test(char) {
  // extract conditions to array
  const chars = ['a', 'b', 'c', 'd'];

  if (chars.includes(char)) {
    console.log('true');
  }
}

2. 少嵌套,早返回

function test(char,num) {
  const chars = ['a', 'b', 'c', 'd'];
 
  // condition 1: char must has value
  if(char){
    // condition 2: must be true
    if (chars.includes(char)) {
        console.log('true');
        // condition 3: must be not zero
        if(num>0){
           console.log('not zero');
        }
    }
  }else {
    throw new Error('no char!');
  }
}

// test results
test(null); // error: no char!
test('a'); // print: true
test('a', 20); // print: true, no char!

修改为

function test(char,num) {
  const chars = ['a', 'b', 'c', 'd'];
 
  // condition 1: char must has value
  if(!char)throw new Error('no char!');
  
  // condition 2: must be true
  if (chars.includes(char)) {
      console.log('true');
      // condition 3: must be not zero
      if(num>0){
         console.log('not zero');
       }
   }
}

更进一步

function test(char,num) {
  const chars = ['a', 'b', 'c', 'd'];
 
  // condition 1: char must has value
  if(!char)throw new Error('no char!');
  
  // condition 2: must be true
  if (!chars.includes(char)) return; 
  
  console.log('true');
  // condition 3: must be not zero
  if(num>0){
     console.log('not zero');
  }
}

3. 使用默认函数参数和解构

function test(fruit, quantity) {
  if (!fruit) return;
  const q = quantity || 1; // if quantity not provided, default to one

  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) { // if quantity not provided, default to one
  if (!fruit) return;
  console.log(`We have ${quantity} ${fruit}!`);
}

//test results
test('banana'); // We have 1 banana!
test('apple', 2); // We have 2 apple!

如果fruit是对象呢?

function test(fruit) { 
  // printing fruit name if value provided
  if (fruit && fruit.name)  {
    console.log (fruit.name);
  } else {
    console.log('unknown');
  }
}

//test results
test(undefined); // unknown
test({ }); // unknown
test({ name: 'apple', color: 'red' }); // apple

改为

// destructing - get name property only
// assign default empty object {}
function test({name} = {}) {
  console.log (name || 'unknown');
}

//test results
test(undefined); // unknown
test({ }); // unknown
test({ name: 'apple', color: 'red' }); // apple

4. 支持Map / Object Literal而不是Switch语句

function test(color) {
  // use switch case to find fruits in color
  switch (color) {
    case 'red':
      return ['apple', 'strawberry'];
    case 'yellow':
      return ['banana', 'pineapple'];
    case 'purple':
      return ['grape', 'plum'];
    default:
      return [];
  }
}

//test results
test(null); // []
test('yellow'); // ['banana', 'pineapple']

改为

// use object literal to find fruits in color
  const fruitColor = {
    red: ['apple', 'strawberry'],
    yellow: ['banana', 'pineapple'],
    purple: ['grape', 'plum']
  };

function test(color) {
  return fruitColor[color] || [];
}

或者

// use Map to find fruits in color
  const fruitColor = new Map()
    .set('red', ['apple', 'strawberry'])
    .set('yellow', ['banana', 'pineapple'])
    .set('purple', ['grape', 'plum']);

function test(color) {
  return fruitColor.get(color) || [];
}

Using 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 test(color) {
  // use Array filter to find fruits in color

  return fruits.filter(f => f.color == 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;

  // condition: all fruits must be red
  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() {
  // condition: short way, all fruits must be red
  const isAllRed = fruits.every(f => f.color == 'red');

  console.log(isAllRed); // false
}

或者

const fruits = [
    { name: 'apple', color: 'red' },
    { name: 'banana', color: 'yellow' },
    { name: 'grape', color: 'purple' }
];

function test() {
  // condition: if any fruit is red
  const isAnyRed = fruits.some(f => f.color == 'red');

  console.log(isAnyRed); // true
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值