需要优化if语句

时间:2019-10-03 07:44:51

标签: javascript if-statement optimization

我制作了一个货币转换器,结果证明条件运算符几乎相同,因此最好通过三元运算符以某种方式进行优化

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

2 个答案:

答案 0 :(得分:2)

不使用独立变量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);

答案 1 :(得分:0)

您可以在顶部为“ 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);