替代数百/数千个if语句

时间:2015-02-23 16:46:12

标签: javascript html5 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语句,这仍然需要输入大量代码。我想知道是否有人能想到解决这个问题的方法,使其稍微减少乏味。我一直试图想出一段时间的解决方案而且我被卡住了。有人可以帮忙吗?感谢

4 个答案:

答案 0 :(得分:5)

为什么不创建一种像

这样的哈希映射
  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]进行访问。

答案 1 :(得分:5)

创建一个对象,其中包含与仅限美元

相关的费率
var rates = {
  usd: 1,
  eur: 0.77,
  gbp: 0.63
}

然后创建一个这样的函数:

function convertRate(src, dest, val){
  if(src=='usd'){
    return val*rates[dest];
  }
  else{
    return val * 1/rates[src] * rates[dest];
  }
}

我们来试试吧!

convertRate('usd','eur',130);
convertRate('eur','gbp',130);

在没有函数的情况下执行相同的操作,只需要一个2d数组就可以获得更好的性能,内存消耗不是问题,但是像这样填充2d数组是单调乏味的。以我建议的方式执行此操作更容易,我认为您不会注意到任何性能差异。

答案 2 :(得分:2)

也许您可以使用尺寸为33x33的二维数组来实现,例如,如果您访问位置(4,10),您将获得第4和第10语言之间的比率。

另一种方法是使用中间货币,如果可能的话:首先从初始货币转换为美元,然后从美元转换为目标货币。

希望这有帮助。

答案 3 :(得分:0)

使用对象:

hardcoded_data =
{
    'uk' : { 'france' : '1.32', 'japan' : '183.79' },
    'japan' : { 'france' : '0.0074', 'japan' : '0.053' }
};