【问题标题】:Need to optimize if statement需要优化if语句
【发布时间】:2019-10-03 15:56:33
【问题描述】:

我做了一个货币转换器,结果发现条件运算符几乎相同,最好通过三元运算符以某种方式优化

var exchan=document.getElementById("exchan");
exchan.addEventListener("click",function(e){
	var numberOne=document.getElementById("numberOne").value;
	var numberTwo=document.getElementById("numberTwo");
	var sExchange;
	var currencyOne=document.getElementById("currencyOne").value;
	var currencyTwo=document.getElementById("currencyTwo").value;
	if(currencyOne=="UAH" && currencyTwo=="USD"){
	numberTwo.value=(numberOne/cursUSD).toFixed(2);
	}
	if(currencyOne=="UAH" && currencyTwo=="EUR"){
	numberTwo.value=(numberOne/cursEUR).toFixed(2);
	}
	if(currencyOne=="UAH" && currencyTwo=="PLN"){
	numberTwo.value=(numberOne/cursPLN).toFixed(2);
	}

},false);

【问题讨论】:

  • 如果 currencyOne 是 UAH,currencyTwo 是否总是这三个之一?美元、欧元、波兰兹罗提? (这将简化逻辑)
  • 为什么条件运算符会更“优化”?
  • @CertainPerformance 稍后我想将 USD 添加到 UAH EUR 到 UAH...

标签: javascript if-statement optimization


【解决方案1】:

代替独立变量cursUSDcursEUR 等,请考虑使用由货币缩写索引的对象。然后,只需在对象上查找转换因子:

const conversions = {
  USD: <value of cursUSD>,
  EUR: <value of cursEUR>,
  PLN: <value of cursPLN>
};
const exchan = document.getElementById("exchan");
exchan.addEventListener("click", function(e) {
  const [numberOneVal, currencyOneVal, currencyTwoVal] = ['numberOne', 'currencyOne', 'currencyTwo']
    .map(id => document.getElementById(id).value);
  if (currencyOneVal === "UAH" && conversions[currencyTwoVal]) {
    document.getElementById("numberTwo").value = (numberOneVal / conversions[currencyTwoVal]).toFixed(2);
  }
}, false);

【讨论】:

  • 我什至会使用二维的查找表,所以,你会做类似if (lookup[currencyOne]) exchangeRate = lookup[currencyOne][currencyTwo] 这样的事情,这样你就不需要额外的逻辑来检查你是否可以转换 from 一些 to 另一个 - 你只需要正确填写查找表。这也可以来自文件和/或生成 - 如果您有UAD -&gt; USD 的汇率,您可以计算反向并填写表格。
【解决方案2】:

您可以在顶部检查“currencyOne”,因为您的所有检查都需要它,并且它会评估一次。 您可以创建一个变量来保存操作的值,因为唯一改变的是currencyTwo 的值,因此您只有一行'numberTwo.value' 赋值。如果 if/else 不适合您进行内部检查,您可以使用开关

 var curOperator;
    if(currencyOne=="UAH")
    {
     if(currencyTwo=="USD") curOperator = cursUSD; 
     else if(currencyTwo=="EUR") curOperator = cursEUR;  
     else if(currencyTwo=="PLN") curOperator = cursPLN; 
     else
        throw;
    }

    numberTwo.value=(numberOne/curOperator).toFixed(2);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-18
    • 2010-09-07
    • 2013-09-17
    • 2017-06-16
    • 1970-01-01
    相关资源
    最近更新 更多