你会如何简化这段 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';
,

你可以试试这个代码。

let resultsConstructionYear = readCookie('constructionYear');
let response = null;

switch(resultsConstructionYear) {
  case 3:
    response = 'Avant 1944';
    break;
  case 4:
    response = 'Entre 1945 et 1974';
    break;
  case 5:
    response = 'Entre 1975 et 1989';
    break;
  case 6:
    response = 'Entre 1990 et 2009';
    break;
  case 7:
    response = 'Après 2010';
    break;
  default:
    response = 'Inconnue';
}

document.getElementById('resultsUserConstructionYear').innerHTML = response;