5个技巧写更好的JavaScript条件语句

当我们在使用JavaScript,条件语句少不了的,下面给出5个技巧让我们写出更好的条件语句。

1、对于多个条件使用Array.includes方法

下面来看一个例子。

// 条件
function test(fruit) {
  if (fruit == 'apple' || fruit == 'strawberry') {
    console.log('red');
  }
}

咋眼一看,这段代码没什么问题。但是试想一下,如果我们的判断条件不止上面两个呢,比如fruit可能值还有cherry(樱桃)等等,那么这时候我们怎么做呢?难道还是要更多的||吗?

让我们通过Array.includes()重写上面的例子。

function test(fruit) {
  // 提取值到数组
  const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries'];

  if (redFruits.includes(fruit)) {
    console.log('red');
  }
}

我们把上面的if判断的值,提取到了数组,然后通过Array.includes方法来判断,这样做,代码看起来更加简洁。

2、少嵌套,尽早返回

接下来让我们来扩展上面的例子:

  • 如果没有fruit提供,就抛出错误提示
  • 如果fruit的数量大于10,就打印fruit
function test(fruit, quantity) {
  const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries'];

  // condition 1: fruit must has value
  if (fruit) {
    // condition 2: must be red
    if (redFruits.includes(fruit)) {
      console.log('red');

      // condition 3: must be big quantity
      if (quantity > 10) {
        console.log('big quantity');
      }
    }
  } else {
    throw new Error('No fruit!');
  }
}

// test results
test(null); // error: No fruits
test('apple'); // print: red
test('apple', 20); // print: red, big quantity

上面例子我们可以看到,达到了三层循环。这是时候,我们可以当发现值无效时,尽早就提供返回。

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

  // condition 1: throw error early
  if (!fruit) throw new Error('No fruit!');

  // condition 2: must be red
  if (redFruits.includes(fruit)) {
    console.log('red');

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

这样做了过后,我们会发现少了嵌套。这样的代码有个好处(想象当你的第一个if代码特别多的时候,else就会在很底部的位置,意思就是你需要滚动才能看到)。

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!

我们经常使用上面的语句来检测null/undefined值,然后来设置一个默认值,这在以前的做法是很明智的,但是其实我们可以通过es6的新特性,设置函数参数的默认值。

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!

这样对于上面的代码,如果参数quantity没有传递值,那么就会使用默认值。这样做是不是更加的简单直接呢?

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

看看上面的例子,如果变量name属性存在,我们就打印出来,否则就打印'unkown'。对于上面的fruit&fruit.name检测,我们可以通过对象属性的解构来实现。

function test({name} = {}) {
  console.log (name || 'unknown');
}

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

我们只需要fruit中的name属性值,那么就可以使用上面的方法,然后name就当做变量在函数中直接使用,替代了上面的fruitt.name,更加方便直接。

4、选择Map/Object,而不是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] || [];
}

或者,你可以使用Map来取得相同的结果。

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

Map和对象的主要区别就是(也就是Map出现的意义)可以做到值和值得对应。

Object 结构提供了“字符串—值”的对应,Map 结构提供了“值—值”的对应,是一种更完善的 Hash 结构实现。如果你需要“键值对”的数据结构,Map 比 Object 更合适。

那这样的话,我们是不是应该禁止使用switch语句呢?答案是否定的,方法没有好坏,取决于你要使用的场景。

对于上面的例子,我们还可以使用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种方法,只能说一句code is funny!

5 、对于所有或者部分的条件判断使用Array.every & Array.some

看看下面的例子,我们想检测是否所有fruit都是红颜色:

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
}

every顾名思义,就是检测所有,只有当每一个值都返回true的时候,最终结果才返回true。还有一点值得说明的就是,every同条件语句判断一样,是惰性的,什么意思呢,因为every是所有的值返回true才最最终结果为true,所以只要执行到一个值返回为false,就不会往下执行了(直接返回false)。相当于条件判断的&。

如果我们想检测是否有一个fruit的颜色为红色呢?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
}

代码很简洁,目的也达到了。同样,some也是惰性的,和条件判断的||很相似。因为some是只要一个返回true,那么最终结果就为true,所以当执行一个代码,得到的结果为true的时候,就不会再往下执行了。

对于数组的方法,Array.map、Array.forEach,还有上面提到的Array.filter,以及一些归并方法reduce、reduceRight。数组迭代+归并,这些方法在实际的代码中,都能提高很大的效率,写出更好的代码。

注:文章和原文差距不多,但是有些话是按照自己理解而成,并不是逐字逐句的翻译。想要查看原文看下面。

原文来源:5 Tips to Write Better Conditionals in JavaScript

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值