优化 JavaScript 条件语句的 5 个实用技巧

作者:巡夜人

时间:2026-10-22

浏览:290

本文介绍五种优化 JavaScript 条件语句的方法:利用 Array.includes 简化多重判断,通过尽早返回减少嵌套层级,使用函数默认参数和解构赋值处理空值,以 Map 或对象字面量替代 switch,以及借助 Array.every 和 Array.some 检查集合条件。这些技巧有助于编写更简洁、易读的代码。

文章目录

引言

在 JavaScript 开发中,条件判断语句的使用频率极高。掌握一些实用的技巧,能够帮助开发者编写出更加简洁、清晰且易于维护的条件逻辑。

利用 Array.includes 处理多重条件

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,还可以进一步减少嵌套层级。注意观察下面的条件 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');
 }
}

通过反转条件 2,现在代码已无嵌套。当逻辑链很长,且希望在不满足某条件时不再执行后续流程时,此技巧非常有用。

然而,并没有硬性规定必须这样做。这取决于个人偏好:对你而言,无嵌套的版本是否比有嵌套的版本(条件 2 嵌套)更好、更易读?

若是我,会选择前一个版本(条件 2 有嵌套)。原因如下:

代码更简短直观,一个嵌套的 if 使结构更清晰。 条件反转会增加思考过程(增加认知负担)。

因此,始终追求更少的嵌套和更早的返回,但切勿过度。感兴趣的话,这里有篇关于该问题的文章以及 StackOverflow 上的讨论:

Avoid Else, Return Early by Tim Oxley StackOverflow discussion on if/else coding style

使用函数默认参数和解构

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

你可能很熟悉以下代码,在 JavaScript 中我们经常需要检查 null / undefined 并赋予默认值:


function test(fruit, quantity) {
 if (!fruit) return;
 const q = quantity || 1; // 如果没有提供 quantity,默认为 1

 console.log(`We have ${q} ${fruit}!`);
}

//测试结果 test('banana'); // We have 1 banana! test('apple', 2); // We have 2 apple!

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


function test(fruit, quantity = 1) { // 如果没有提供 quantity,默认为 1
 if (!fruit) return;
 console.log(`We have ${quantity} ${fruit}!`);
}

//测试结果 test('banana'); // We have 1 banana! test('apple', 2); // We have 2 apple!

是不是更简单、直观?请注意,所有函数参数都可以有默认值。例如,我们也可以为 fruit 赋予默认值:function test(fruit = 'unknown', quantity = 1)。

那么如果 fruit 是一个对象(Object)呢?还能使用默认参数吗?


function test(fruit) { 
 // 如果有值,则打印出来
 if (fruit && fruit.name) {
  console.log (fruit.name);
 } else {
  console.log('unknown');
 }
}

//测试结果 test(undefined); // unknown test({ }); // unknown test({ name: 'apple', color: 'red' }); // apple

观察上述例子,当水果名称属性存在时,我们希望将其打印出来,否则打印“unknown”。我们可以通过默认参数和解构赋值来避免写出 fruit && fruit.name 这种条件判断。


// 解构 —— 只得到 name 属性
// 默认参数为空对象 {}
function test({name} = {}) {
 console.log (name || 'unknown');
}

//测试结果 test(undefined); // unknown test({ }); // unknown test({ name: 'apple', color: 'red' }); // apple

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

我们还使用 {} 作为其默认值。如果不这么做,在执行 test(undefined) 时,你会得到一个错误 Cannot destructure property name of 'undefined' or 'null'.,因为 undefined 上并没有 name 属性。(译者注:这里不太准确,其实因为解构只适用于对象(Object),而不是因为undefined 上并没有 name 属性(空对象上也没有)。参考解构赋值 - MDN) 如果你不介意使用第三方库的话,有一些方法可以帮助减少空值(null)检查:

使用 Lodash get 函数

使用 Facebook 开源的 idx 库(需搭配 Babeljs)

这里有一个使用 Lodash 的例子:


// 使用 lodash 库提供的 _ 方法
function test(fruit) {
 console.log(_.get(fruit, 'name', 'unknown'); // 获取属性 name 的值,如果没有,设为默认值 unknown
}

//测试结果 test(undefined); // unknown test({ }); // unknown test({ name: 'apple', color: 'red' }); // apple

你可以在这里运行演示代码。另外,如果你偏爱函数式编程(FP),可以选择使用 Lodash fp——函数式版本的 Lodash(方法名变为 get 或 getOr)。

Map / Object 替代 switch

相较于 switch,Map / Object 也许是更好的选择

让我们看下面的例子,我们想要根据颜色打印出各种水果:


function test(color) {
 // 使用 switch case 来找到对应颜色的水果
 switch (color) {
  case 'red':
   return ['apple', 'strawberry'];
  case 'yellow':
   return ['banana', 'pineapple'];
  case 'purple':
   return ['grape', 'plum'];
  default:
   return [];
 }
}

//测试结果 test(null); // [] test('yellow'); // ['banana', 'pineapple']

上述代码看起来并没有错,但就我个人而言,它显得冗长。同样的结果可以通过对象字面量来实现,语法也更加简洁:


// 使用对象字面量来找到对应颜色的水果
 const fruitColor = {
  red: ['apple', 'strawberry'],
  yellow: ['banana', 'pineapple'],
  purple: ['grape', 'plum']
 };

function test(color) {
 return fruitColor[color] || [];
}

或者,你也可以使用 Map 来实现同样的效果:


// 使用 Map 来找到对应颜色的水果
 const fruitColor = new Map()
  .set('red', ['apple', 'strawberry'])
  .set('yellow', ['banana', 'pineapple'])
  .set('purple', ['grape', 'plum']);

function test(color) {
 return fruitColor.get(color) || [];
}

Map 是 ES2015 引入的新的对象类型,允许你存放键值对。

那是不是说我们应该禁止使用 switch 语句? 别把自己限制住。我自己会在任何可能的时候使用对象字面量,但是这并不是说我就不用 switch,这得视场景而定。 Todd Motto 有一篇文章深入讨论了 switch 语句和对象字面量,你也许会想看看。

懒人版:重构语法

就以上的例子,事实上我们可以通过重构我们的代码,使用 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) {
 // 使用 Array filter 来找到对应颜色的水果

 return fruits.filter(f => f.color == color);
}

解决问题的方法永远不只一种。对于这个例子我们展示了四种实现方法。Coding is fun!

使用 Array.every 和 Array.some 处理条件

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

最后一个小技巧更多地是关于使用新的(也不是很新了)JavaScript 数组函数来减少代码行数。观察以下的代码,我们想要检查是否所有的水果都是红色的:


const fruits = [
  { name: 'apple', color: 'red' },
  { name: 'banana', color: 'yellow' },
  { name: 'grape', color: 'purple' }
 ];

function test() {
 let isAllRed = true;

 // 条件:所有的水果都必须是红色
 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() {
 // 条件:(简短形式)所有的水果都必须是红色
 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() {
 // 条件:至少一个水果是红色的
 const isAnyRed = fruits.some(f => f.color == 'red');

 console.log(isAnyRed); // true
}

总结

总结

以上所述是小编给大家介绍的分享5个小技巧让你写出更好的 JavaScript 条件语句,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对本站网站的支持!

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章