javascript - 替代成百上千的 if 语句

标签 javascript html if-statement

<分区>

我正在用 html5 和 javascript 编写一个货币转换应用程序,并对转换率进行硬编码。问题是我希望能够在 33 种货币之间进行转换。这会产生一个问题,因为我能想到的唯一方法是使用 if 语句,这意味着我将不得不编写 1056 个 if 语句。 即

if (homeCountry = "uk" and destinationCountry = "france") {
    rate = 1.32;
}
if (homeCountry = "uk" and destinationCountry = "japan") {
   rate = 183.79;
}

对于所有英国转换,然后

if (homeCountry = "japan" and destinationCountry = "france") {
   rate = 0.0074;
}
if (homeCountry = "japan" and destinationCountry = "china") {
    rate = 0.053;
}

对于所有日语转换等

即使使用 switch 语句,这仍然需要输入大量代码。我想知道是否有人能想出一个解决方案来让它稍微不那么乏味。一段时间以来,我一直在尝试寻找解决方案,但我被卡住了。谁能帮忙?谢谢

最佳答案

为什么不创建一种像这样的 HashMap

  conversions: {
    uk: {
      france: 1.12,
      japan: 2.12
    },
    france: {
      uk: 1.22,
      japan: 2.3
    },
    japan: {
      france: 2.2,
      uk: 3.4
    }
  }

然后您可以通过 conversions[homeCountry][destinationCountry] 访问。

关于javascript - 替代成百上千的 if 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28678806/

相关文章:

html - 无法相对于复选框垂直对齐标签

Java 结束语

javascript - 寻找 HTML 选择的任何漂亮或 "WOW"效果

javascript - 使用 jQuery 过滤 html 表

html - 我应该使用什么?十六进制代码、RGB 代码或代码中的颜色名称?

c# - 使用 if 语句时,当前上下文中不存在该名称

MySql 在 IF 子句中使用 DATEDIFF

javascript - React 开发服务器无法运行 Apple Macbook pro M1

javascript - 如何在 Javascript/Angularjs 中检测用户来自哪里的 url?

javascript - 如何使用 React 中的 JSON 文件中的每个值生成组件?