首页 > 语言 > JavaScript > 正文

分享5个小技巧让你写出更好的 JavaScript 条件语句

2024-05-06 15:28:36
字体:
来源:转载
供稿:网友

在使用 JavaScript 时,我们常常要写不少的条件语句。这里有五个小技巧,可以让你写出更干净、漂亮的条件语句。

1. 使用 Array.includes 来处理多重条件

举个栗子 :

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

乍一看,这么写似乎没什么大问题。然而,如果我们想要匹配更多的红色水果呢,比方说『樱桃』和『蔓越莓』?我们是不是得用更多的 || 来扩展这条语句?

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

function test(fruit) { // 把条件提取到数组中 const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries']; if (redFruits.includes(fruit)) {  console.log('red'); }}

我们把红色的水果(条件)都提取到一个数组中,这使得我们的代码看起来更加整洁。

2. 少写嵌套,尽早返回

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

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

如果该水果的数量大于 10,将其打印出来。

function test(fruit, quantity) { const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries']; // 条件 1:fruit 必须有值 if (fruit) {  // 条件 2:必须为红色  if (redFruits.includes(fruit)) {   console.log('red');   // 条件 3:必须是大量存在   if (quantity > 10) {    console.log('big quantity');   }  } } else {  throw new Error('No fruit!'); }}

// 测试结果
test(null); // 报错:No fruits
test('apple'); // 打印:red
test('apple', 20); // 打印:red,big quantity

让我们来仔细看看上面的代码,我们有:

1 个 if/else 语句来筛选无效的条件
3 层 if 语句嵌套(条件 1,2 & 3)

就我个人而言,我遵循的一个总的规则是当发现无效条件时尽早返回。
/_ 当发现无效条件时尽早返回 _/

function test(fruit, quantity) { const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries']; // 条件 1:尽早抛出错误 if (!fruit) throw new Error('No fruit!'); // 条件2:必须为红色 if (redFruits.includes(fruit)) {  console.log('red');  // 条件 3:必须是大量存在  if (quantity > 10) {   console.log('big quantity');  } }}

如此一来,我们就少写了一层嵌套。这是种很好的代码风格,尤其是在 if 语句很长的时候(试想一下,你得滚动到底部才能知道那儿还有个 else 语句,是不是有点不爽)。

如果反转一下条件,我们还可以进一步地减少嵌套层级。注意观察下面的条件 2 语句,看看是如何做到这点的:
/_ 当发现无效条件时尽早返回 _/

function test(fruit, quantity) { const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries']; if (!fruit) throw new Error('No fruit!'); // 条件 1:尽早抛出错误 if (!redFruits.includes(fruit)) return; // 条件 2:当 fruit 不是红色的时候,直接返回 console.log('red'); // 条件 3:必须是大量存在 if (quantity > 10) {  console.log('big quantity'); }}            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选