5个技巧教你写更好的JavaScript条件语句 - 图1

在使用JavaScript时,我们处理了很多条件逻辑判断,这里有5个技巧可以帮助您编写更好/更简洁的条件语句。

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

  1. // condition
  2. function test(fruit) {
  3. if (fruit == 'apple' || fruit == 'strawberry') {
  4. console.log('red');
  5. }
  6. }

乍一看,上面的例子看起来不错。然而,如果我们得到更多的红色水果,比如cherrycranberries?我们是否会更多地使用||来扩展判断表达式?

我们可以使用Array.includes重写上面的条件

  1. function test(fruit) {
  2. // extract conditions to array
  3. const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries'];
  4. if (redFruits.includes(fruit)) {
  5. console.log('red');
  6. }
  7. }

我们将red fruits(条件)提取到数组中。通过这样做,代码看起来更整洁。

2.较少嵌套,尽早使用return

让我们扩展前面的示例以包含另外两个条件:

  • 如果没有提供水果,抛出错误
  • 如果超过10,则接受并打印水果数量
  1. function test(fruit, quantity) {
  2. const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries'];
  3. // condition 1: fruit must has value
  4. if (fruit) {
  5. // condition 2: must be red
  6. if (redFruits.includes(fruit)) {
  7. console.log('red');
  8. // condition 3: must be big quantity
  9. if (quantity > 10) {
  10. console.log('big quantity');
  11. }
  12. }
  13. } else {
  14. throw new Error('No fruit!');
  15. }
  16. }
  17. // test results
  18. test(null); // error: No fruits
  19. test('apple'); // print: red
  20. test('apple', 20); // print: red, big quantity

看看上面的代码,我们有:

  • 1 if / else语句过滤掉无效条件
  • 3级嵌套if语句(条件1,2和3)

我个人遵循的一般规则是在发现无效条件时提前 return

  1. /_ return early when invalid conditions found _/
  2. function test(fruit, quantity) {
  3. const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries'];
  4. // condition 1: throw error early
  5. if (!fruit) throw new Error('No fruit!');
  6. // condition 2: must be red
  7. if (redFruits.includes(fruit)) {
  8. console.log('red');
  9. // condition 3: must be big quantity
  10. if (quantity > 10) {
  11. console.log('big quantity');
  12. }
  13. }
  14. }

通过这样做,我们有一个较少级别的嵌套语句。这种编码风格很好,特别是当你有很长的if语句时(想象你需要滚动到最底层才知道有一个else语句,这让人很不爽)。

如果通过反转条件并提前return,我们可以进一步减少嵌套。请查看下面的条件2,看看我们是如何做到的:

/_ return early when invalid conditions found _/

function test(fruit, quantity) {
  const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries'];

  if (!fruit) throw new Error('No fruit!'); // condition 1: throw error early
  if (!redFruits.includes(fruit)) return; // condition 2: stop when fruit is not red

  console.log('red');

  // condition 3: must be big quantity
  if (quantity > 10) {
    console.log('big quantity');
  }
}

通过反转条件2的条件,我们的代码现在没有嵌套语句。当我们有很长的逻辑时,这种技术非常有用,我们希望在条件不满足时停止进一步的处理。

但是,这样做并不是一件难事。问问自己,这个版本(没有嵌套)比前一个更好/更可读(条件2嵌套)?

对我来说,我只是把它留作以前的版本(条件2嵌套)。这是因为:

  • 代码简短直接,嵌套if更清晰
  • 反转条件可能会引发更多的思考过程(增加认知负荷)

因此,始终旨在尽早减少筑巢和回归,但不要过度。如果您感兴趣,有一篇文章和StackOverflow讨论会进一步讨论这个主题:

3.使用默认功能参数和解构

我想下面的代码可能看起来很熟悉,我们总是需要检查null/ undefined值并在使用JavaScript时分配默认值:

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!

实际上,我们可以q通过分配默认函数参数来消除变量。

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 = ‘unknown’, quantity = 1)。

如果我们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

看看上面的例子,我们想要打印水果名称,如果它可用,或者我们将打印未知。我们可以避免fruit && fruit.name使用默认函数参数和解构进行条件检查。

// 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

由于我们只需要name来自水果的属性,我们可以使用构造参数{name},然后我们可以name在代码中使用变量代替fruit.name

我们还将空对象指定{}为默认值。如果我们不这样做,你在执行行时会出错test(undefined)- Cannot destructure property name of 'undefined' or 'null'.因为name属性为undefined。

如果您不介意使用第三方库,有几种方法可以减少空检查:

  • 使用Lodash get功能
  • 使用Facebook开源的idx库(与Babeljs)

以下是使用Lodash的示例:

// Include lodash library, you will get _
function test(fruit) {
  console.log(__.get(fruit, 'name', 'unknown'); // get property name, if not available, assign default value 'unknown'
}

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

您可以在此处运行演示代码。此外,如果您是功能编程(FP)的粉丝,您可以选择使用Lodash fp,Lodash的功能版本(方法更改为getgetOr)。

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']

上面的代码似乎没有错,但我觉得它很冗长。使用具有更清晰语法的object literal可以实现相同的结果:

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

或者,您可以使用Map来实现相同的结果:

Map是自ES2015以来可用的对象类型,允许您存储键值对。

我们应该禁止使用switch语句吗? 不要局限于此。就个人而言,我尽可能使用对象文字,但我不会设置硬规则来阻止它,使用对你的场景有意义的。

TL; DR; 重构语法

对于上面的例子,我们实际上可以使用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);
}

总有不止一种方法可以达到相同的效果。我们用相同的例子展示了4次不同写法。编码很有趣!

5.对所有/部分标准使用Array.every和Array.some

最后一个提示更多的是利用新的(但不是那么新的)Javascript Array函数来减少代码行。看下面的代码,我们想检查所有水果是否都是红色的:

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
}

代码太长了!我们可以使用Array.every来精简减少行数:

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
}

现在更干净了吗?以类似的方式,如果我们想测试任何水果是否是红色,我们可以用Array.some它来实现它。

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
}

总结

让我们一起生成更多可读代码。我希望你能在本文中学到一些新东西。

就这样。快乐的编码!

译者总结:能尽量不写太多条件判断就不写,如果写多了,一定要优化减少,不然代码阅读体验维护成本会较高,改掉坏习惯,手写一首好代码,从没一点学起。

以下是个人给前端组员总结个人学习代码锻炼的方法,可参考,也欢迎指出问题,以及分享你认为更好的学习方法:

手写好代码进阶方式:

  • 1、尽量熟悉编程所有语言特性、方法等(最基本的了);
  • 2、改掉以前习惯写法,代码规范上严格要求自己(每次要写时,停下,换一种写法,因为习惯问题,你会一直默默写着糟糕的代码,所以改掉糟糕的写法习惯,GitHub能找到各种编程语言的代码编写规范);
  • 3、多次重构自己的代码,思考是否有好的写法(这个会加深印象,好处就是以后你写到这种代码就直接用做好的写法来实现,相关这方面代码重构书籍也是要看的)
  • 4、GitHub看别人的代码,npm模块或者自己技术栈相关demo、组件;(你会明显感到别人写的好,自己写不出,学习理解了相信成长很大)
  • 5、如果到第3、4点你发现很难进步提升,别人代码也看不明白,可能是一些编程思想没理解,或者是设计模式等。设计模式很大程度影响着一个人开发一个复杂功能的代码结构分类,组织、实现形式。

PS:以上除第一点外,其他点学习无规定顺序。