es6之更优雅的条件语句

在使用JavaScript时,条件判断是经常会用到的,一些简单的判断条件还可以接受,当遇到比较复杂多重条件时就比较恶心了。这里使用es6的小技巧使判断更优雅。

1、使用 Arrary.includes 处理多重条件(返回布尔值 true 或 false)

比如:

function test(fruit) {
  if (fruit == "apple" || fruit == "orange") {
    console.log("red");
  } else {
     console.log('blue')
  }  
}

当两个条件时,还比较简单,但是当条件增多这种写法就太麻烦了。可以使用如下:

1 function test2(fruit) {
2   const redFruits = ['apple', 'cherry', 'strawberry'];
3   if(redFruits.includes(fruit)) {
4     console.log('red')
5   } else {
6     console.log('blue')
7   }
8 }

将条件放到一个数组中,简便了好多。

2、少写嵌套,尽早返回

为之前的例子添加两个条件:

如果没有提供水果,抛出错误。

如果水果数量大于10,则打印。

 1 function test3(fruit, quantity) {
 2   const redFruits = ['apple', 'cherry', 'strawberry'];
 3   if(!fruit) console.error('error');
 4   if(redFruits.includes(fruit)) {
 5     console.log('red');
 6     if(quantity > 10) {
 7       console.log('big quantity')
 8     }
 9   }
10 }
11 
12 // test3(null)
13 // test3('apple')
14 test3('apple', 20)
test3

上面这个有问题,完全可以 写 并语句 && 。时刻记着 return 它可以阻止后面函数的执行。减少无必要的判断。

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

在JavaScript 中 我们经常需要检查 null 或 undefined 并赋予默认值。

1 function test4(fruit, quantity) {
2   if(!fruit) return;
3   const q = quantity || 0;
4   console.log(`we have ${q} ${fruit}!`)
5 }
6 
7 test4('banana');  // we have 0 banana!
8 test4('apple', 3);  // we have 3 apple!

事实上,我们可以通过函数的默认参数来去掉变量q

1 function test5(fruit, quantity = 1) {
2   if(!fruit) return;
3   const q = quantity || 0;
4   console.log(`we have ${quantity} ${fruit}!`)
5 }
6 test5('banana');  // we have 1 banana!
7 test5('apple', 3);  // we have 3 apple!

注意:所有的函数参数都可以有默认值。

那如果fruit 是一个对象呢?如何使用默认值?

 1 function test6(fruit) {
 2   if(fruit && fruit.name) {
 3     console.log(fruit.name);
 4   } else {
 5     console.log('unknown')
 6   }
 7 }
 8 test6(undefined); // unknown
 9 test6({ });  // unknown
10 test6({name: 'apple', color: 'red'}); // apple

上面是 当水果名字属性存在时,将其打印,否则打印 unknown。

我们可以通过默认参数 和 解构赋值的方法来避免 写出 fruit && fruit.name 这种条件。

1 // 解构 -- 只得到name属性。默认参数为空对象 {}
2 function test7({name} = {}) {
3   console.log(name || 'unknown');
4 }
5 test7(undefined); // unknown
6 test7({ });  // unknown
7 test7({name: 'apple', color: 'red'}); // apple

既然我们只需要fruit 的name属性,我们可以使用{name} 将其解构出来,之后在代码中就可以使用name代替fruit.name了。

我们还使用{}作为默认值,如果不使用默认值,当 undefined 时会报错。cannot destructure property name of 'undefined' or 'null'。

注意:解构 ---- 只适用于对象。

4、相比 switch 、Map / Object 也许是更好地选择。

如下我们想要根据颜色打印水果:

 1 function test8(color) {
 2   switch(color) {
 3     case 'red':
 4       return ['apple', 'strawberry'];
 5     case 'yellow':
 6       return ['banana', 'pineapple'];
 7     case 'purple':
 8       return ['grape', 'plum'];
 9     default:
10       return [];
11   }
12 }
13 console.log(test8(null)); // []
14 console.log(test8(undefined)); // []
15 console.log(test8('red')); // [ 'apple', 'strawberry' ]

同样的结果可以通过对象字面量来实现,语法更简洁,如下:

 1 const fruitColor = {
 2   red: ['apple', 'strawberry'],
 3   yellow: ['banana', 'pineapple'],
 4   purple: ['grape', 'plum']
 5 };
 6 function test9(color) {
 7   return fruitColor[color] || [];
 8 }
 9 console.log(test9(null)); // []
10 console.log(test9(undefined)); // []
11 console.log(test9('red')); // [ 'apple', 'strawberry' ]

也可以使用Map来实现同样效果:

1 // 使用Map找到对应颜色的水果
2 const fruitColors = new Map().set('red', ['apple', 'strawberry']).set('yellow', ['banana', 'pineapple']).set('purple', ['grape', 'plum']);
3 function test10(color) {
4   return fruitColors.get(color) || [];
5 }
6 console.log(test10(null)); // []
7 console.log(test10(undefined)); // []
8 console.log(test10('red')); // [ 'apple', 'strawberry' ]

Map 是es6引入的新的对象类型,允许存放键值对。但是和json不一样,不能像 jsonObj.key 那样取值,会得到undefined。只能 mapObj.get(key) 取值。详细看Map。

还用一种 重构语法:

 1 const fruits = [
 2   {
 3     name: 'apple',
 4     color: 'red'
 5   },
 6   {
 7     name: 'banana',
 8     color: 'yellow'
 9   },
10   {
11     name: 'grape',
12     color: 'purple'
13   },
14   {
15     name: 'orange',
16     color: 'yellow'
17   }
18 ];
19 function test11(color) {
20   // 使用 Array.filter 方法
21   return fruits.filter(f => f.color == color)
22 }
23 console.log(test11('yellow')); // [ { name: 'banana', color: 'yellow' },{ name: 'orange', color: 'yellow' } ]

5、使用 Array.every 和 Array.some 来处理全部 / 部分满足条件:

如下代码是要检查是否所有水果都是红色的:

1 function test12() {
2   let isAllRed = true;
3   for(let f of fruits) {
4     if(!isAllRed) break;
5     isAllRed = (f.color == 'red');
6   }
7   console.log(isAllRed);
8 }
9 test12() // false

我们可以通过 Array.every 来减少代码量:

1 function test13() {
2   const isAllRed = fruits.every(f => f.color == 'red');
3   console.log(isAllRed);
4 }
5 test13()  // false

类似的检查是否至少有一个是红色的,可以使用Array.some

1 function test14() {
2   const isAngRed = fruits.some(f => f.color == 'red');
3   console.log(isAngRed)
4 }
5 test14() // true

后续 es6 一些 更加简单方便的方法再添加。

function test14() {
const isAngRed = fruits. some( f => f. color == 'red');
console. log( isAngRed)
}
test14() // true

猜你喜欢

转载自www.cnblogs.com/xguoz/p/10146931.html