简体   繁体   English

需要优化if语句

[英]Need to optimize if statement

I make a currency converter and as a result it turns out that the condition operators are almost identical, it would be better to somehow optimize through the ternary operator我做了一个货币转换器,结果发现条件运算符几乎相同,最好通过三元运算符以某种方式优化

 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);

Instead of standalone variables cursUSD , cursEUR , etc, onsider using an object indexed by the currency abbreviation.代替独立变量cursUSDcursEUR等,使用由货币缩写索引的 object。 Then, just look up the conversion factor on the object:然后,只需在 object 上查找转换系数:

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);

You can make the check for 'currencyOne' on the top part, since all your check require it, and it will evaluate once.您可以在顶部检查“currencyOne”,因为您的所有检查都需要它,并且它会评估一次。 You can create a variable to hold the value of the operation, since the onlything changing is the value of the currencyTwo, so that you only have one line of 'numberTwo.value' assignment.您可以创建一个变量来保存操作的值,因为唯一改变的是currencyTwo 的值,因此您只有一行'numberTwo.value' 赋值。 You could use a switch if the if/else does not suite you for the inner checkings如果 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM