使用对象文字 - [en-US] 替换您的 switch 语句和多个“if and else”。

2025-06-07

使用对象文字 - [en-US] 替换您的 switch 语句和多个“if and else”。

替代文本

那么首先,什么是 Switch 语句?

开关是一个接收数据的函数,它会分析该数据,如果该数据等于我们的某个案例,它会执行该案例中的指令并返回一个值。



function UserPolicy(type) {
  switch(type) {
    case 'admin':
      return 'This User is Admin!'
      break
    case 'client':
      return 'This User is Client!'
      break
    case 'salesman':
      return 'This User is Salesman!'
      break
    default:
      return 'Ops, this guy doesn\'t have user profile'
  }
}

UserPolicy() // 'Ops, this guy doesn't have user profile'
UserPolicy('admin') // "This User is Admin!"


Enter fullscreen mode Exit fullscreen mode

它类似于 if 和 else 语句,但它应该评估单个值 - 在 switch 内部我们使用 case 来评估每个值。

如果你大量使用 else if 语句,那就大错特错了。通常情况下,你应该使用 switch 之类的语句,因为它更符合你的目的和意图。以下是一些 else if 的滥用情况:



function UserPolicy(type) {
let userType
if (type === 'admin') {
userType = 'This User is Admin!'
} else if (type === 'client') {
userType = 'This User is Client!'
} else if (type === 'salesman') {
userType = 'This User is Salesman!'
} else {
userType = 'Ops, this guy doesn\'t have user profile'
}

return User is type: </span><span class="p">${</span><span class="nx">userType</span><span class="p">}</span><span class="s2">
}

Enter fullscreen mode Exit fullscreen mode




开关问题

switch 存在诸多问题,从其过程控制流到其处理代码块的方式看起来不太标准。JavaScript 的其余部分都使用花括号,而 switch 却没有。从语法上讲,它并非 JavaScript 的最佳选择,其设计也同样如此。我们不得不在每个 case 中手动添加 break; 语句,这会导致调试困难,并且一旦忘记,case 语句中还会嵌套错误!我们必须谨慎对待这个问题。

在 JavaScript 中,我们经常使用对象查找,而对于某些事物,我们通常不会考虑使用 switch 语句——那么为什么不使用对象字面量来代替 switch 语句呢?对象更加灵活,具有更好的可读性和可维护性,而且我们不需要手动 break; 每一个 case。由于它们是标准对象,因此对 JavaScript 新手来说也更加友好。

不使用 switch 的原因

  • 随着“case”数量的增加,对象(哈希表)的性能会优于 switch 的平均成本(case 的顺序)。对象方法是一种哈希表查找,switch 必须评估每个 case,直到找到匹配项并中断。

  • 更易于维护和阅读。我们也不必担心 break; 语句和 case 会失败——它只是一个简单的对象。

通常,我们会在函数内部放置一个 switch 语句,并获取一个返回值。让我们在这里做同样的事情,并将 switch case 变成一个可用的函数,并返回一个对象字面量:



function UserPolicy(type) {
// We create a const that receives an object and each of its properties.
// will be the values corresponding to our types
const Users = {
admin: 'This User is Admin!',
client: 'This User is Client!',
salesman: 'This User is Salesman!',
default: 'Ops, this guy doesn\'t have user profile'
}

return Users[type] || Users.default
}

UserPolicy() // 'Ops, this guy doesn't have user profile'
UserPolicy('admin') // "This User is Admin!"

Enter fullscreen mode Exit fullscreen mode




概述

对象字面量是 JavaScript 中更自然的流程控制方式,相比之下,switch 有点老旧、笨重,而且容易出现难以调试的错误。对象更易于扩展和维护,而且我们可以更好地测试它们。它们也是设计模式的一部分,并且在日常编程任务中非常常用。对象字面量可以包含函数以及任何其他 Object 类型,这使得它们非常灵活!字面量中的每个函数也具有函数作用域,因此我们可以从父函数返回闭包。

//我不是在规定规则——这只是解决我们日常问题的另一种方式

文章来源:https://dev.to/tauantcamargo/replace-your-switch-statement-and-multiple-if-and-else-using-object-literals-en-us-1dec
PREV
使用 CSS / Tailwind 的下拉菜单
NEXT
使用 Vite 拆分供应商块并异步加载它们