5 tips to write better conditionals

  • 多重判断中使用Array.includes
function test(fruit) {
  const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries'];
  if (redFruits.includes(fruit)) {
    console.log('red');
  }
}
复制代码
  • 少嵌套,早返回(发现无效的条件时,及早return)
function test(fruit, quantity) {
  const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries'];
  if (!fruit) throw new Error('No fruit!'); 
  if (!redFruits.includes(fruit)) return; 
  console.log('red');
  if (quantity > 10) {
    console.log('big quantity');
  }
}
复制代码
  • 使用默认参数和解构
function test(fruit, quantity = 1) { 
  if (!fruit) return;
  console.log(`We have ${quantity} ${fruit}!`);
}
复制代码
  • 倾向对象遍历而不是switch语句
  const fruitColor = {
    red: ['apple', 'strawberry'],
    yellow: ['banana', 'pineapple'],
    purple: ['grape', 'plum']
  };
function test(color) {
  return fruitColor[color] || [];
}
复制代码
  • 对 全部/部分判断 使用Array.every/Array.some
const fruits = [
    { name: 'apple', color: 'red' },
    { name: 'banana', color: 'yellow' },
    { name: 'grape', color: 'purple' }
  ];
const isAllRed = fruits.every(f => f.color == 'red');
复制代码

作者:call_me_R

链接:juejin.im/post/5c4fa7…

转载于:https://juejin.im/post/5c4ff1ad6fb9a049a71237bc

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值