0
点赞
收藏
分享

微信扫一扫

如何写好javascript条件


1.多重判断时使用 Array.includes

2.更少的嵌套,尽早 return

3.使用默认参数和解构

4.倾向于遍历对象而不是 Switch 语句

5.对 所有/部分 判断使用 Array.every & Array.some

6.总结

1.多重判断时使用 Array.includes

让我们看一下下面这个例子:

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

第一眼,上面这个例子看起来没问题。如果我们有更多名字叫 ​​cherry​​​ 和 ​​cranberries​​​ 的红色水果呢?我们准备用更多的 ​​||​​来拓展条件语句吗?

我们可以用 ​​Array.includes​​​ ​​(Array.includes)​​重写条件语句。

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

if (redFruits.includes(fruit)) {
cons


举报

相关推荐

0 条评论