Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
207 views
in Technique[技术] by (71.8m points)

jquery - How would you simplify this piece of javascript code?

looking for some suggestions here to improve my coding.

How would you make this code shorter/more efficient?

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";
}
question from:https://stackoverflow.com/questions/65870954/how-would-you-simplify-this-piece-of-javascript-code

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Create an object or a Map of text by the construction year's number. If the number doesn't exist on the object use 'Inconnue' as a fallback:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...