优化if / else语句

时间:2019-10-04 05:35:34

标签: javascript if-statement optimization

我编写了以下代码来模拟和简化应用程序中发生的事情。

在这种简化中,我具有执行相同代码的if和else分支

async function manipulDom(e) {
  const URItwo = `https://bank.gov.ua/NBUStatService/v1/statdirectory/exchange?json`;
  let response = await fetch(URItwo);
  var data = await response.json();
  console.log(data);
  for (var key in data) {
    if (data[key].cc == "USD") {
      rateone.innerHTML =
        data[key].txt + ` ` + data[key].rate.toFixed(2) + `грн`;
      cursUSD = data[key].rate.toFixed(2);
      console.log(cursUSD);
    } else if (data[key].cc == "EUR") {
      ratetwo.innerHTML =
        data[key].txt + ` ` + data[key].rate.toFixed(2) + `грн`;
      cursEUR = data[key].rate.toFixed(2);
      console.log(cursEUR);
    } else if (data[key].cc == "PLN") {
      ratetree.innerHTML =
        data[key].txt + ` ` + data[key].rate.toFixed(2) + `грн`;
      cursPLN = data[key].rate.toFixed(2);
      console.log(cursPLN);
      return;
    }
  }
}

2 个答案:

答案 0 :(得分:3)

使用由货币缩写索引的对象代替:

const cursObj = {
  USD: <value of cursUSD>,
  EUR: <value of cursEUR>,
  PLN: <value of cursPLN>
};
const rateElementsByCurrency = {
  USD: rateone,
  EUR: rateTwo,
  PLN: rateThree
}

async function manipulDom(e) {
  const URItwo = `https://bank.gov.ua/NBUStatService/v1/statdirectory/exchange?json`;
  const response = await fetch(URItwo);
  const data = await response.json();
  data.forEach((obj) => {
    const { cc } = obj;
    if (cursObj[cc]) {
      cursObj[cc] = obj.rate.toFixed(2);
      rateElementsByCurrency[cc].textContent = obj.txt + ` ` + cursObj[cc] + `грн`;
      // If you're familiar with template literals, then you can do instead:
      // rateElementsByCurrency[cc].textContent = `${obj.txt} ${cursObj[cc]}грн`;
    }
  });
}

由于dataarray而不是对象,因此请使用forEach对其进行迭代-请勿使用`for..in来遍历数组。

由于要将 text 放入rateElementsByCurrency元素而不是HTML中,因此应使用textContent而不是innerHTML,它更加安全,快捷,并且更可预测。

答案 1 :(得分:0)

尝试一下

async function manipulDom(e) {
  const URItwo = `https://bank.gov.ua/NBUStatService/v1/statdirectory/exchange?json`;
  const response = await fetch(URItwo);
  const data = await response.json();
  var cc = ["USD", "EUR", "PLN"];
  var exchangeRates = {};  
  for(value of data){
      if(cc.includes(value.cc)){
          let index = cc.indexOf(value.cc);
          cc.splice(index,index+1);
          value.rate = Number(value.rate).toFixed(2);
          exchangeRates[value.cc] = value;  
      }
      if(cc.length < 1){break;}

  }
  console.log(exchangeRates);
}
manipulDom();

相关问题