你会如何简化这段javascript代码?

在这里寻找一些建议来改进我的编码。

你如何使这段代码更短/更有效?

var resultsConstructionYear = readCookie('constructionYear');
if (resultsConstructionYear == 3) {
    document.getElementById('resultsUserConstructionYear').innerHTML = "Avant 1944";
} else if (resultsConstructionYear == 4) {
    document.getElementById('resultsUserConstructionYear').innerHTML = "Entre 1945 et 1974";
} else if (resultsConstructionYear == 5) {
    document.getElementById('resultsUserConstructionYear').innerHTML = "Entre 1975 et 1989";
} else if (resultsConstructionYear == 6) {
    document.getElementById('resultsUserConstructionYear').innerHTML = "Entre 1990 et 2009";
} else if (resultsConstructionYear == 7) {
    document.getElementById('resultsUserConstructionYear').innerHTML = "Après 2010";
} else {
    document.getElementById('resultsUserConstructionYear').innerHTML = "Inconnue";
}

回答

按施工年份编号创建对象或文本地图。如果对象上不存在该数字,则'Inconnue'用作后备:

const textByNumber = {
  3: 'Avant 1944',
  4: 'Entre 1945 et 1974',
  5: 'Entre 1975 et 1989',
  ...
};

const resultsConstructionYear = readCookie('constructionYear');

document.getElementById('resultsUserConstructionYear')
  .innerHTML = textByNumber[resultsConstructionYear] || 'Inconnue';

  • The amount of times I forget objects with numeric indexes are valid is annoying 🙂
  • JS The Good (?) Parts 🙂

以上是你会如何简化这段javascript代码?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>