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

Deb*_*rah -1 javascript arrays optimization performance jquery

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

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

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";
}
Run Code Online (Sandbox Code Playgroud)

Ori*_*ori 5

按施工年份编号创建对象或文本地图。如果对象上不存在该数字,则'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';
Run Code Online (Sandbox Code Playgroud)

  • 我经常忘记带有数字索引的对象是有效的,这很烦人:) (2认同)
  • JS 好的(?)部分:) (2认同)