11484 sujets

JavaScript, DOM et API Web HTML5

Hello,

Vous simplifieriez comment cette condition ?


if (currentIndex == 0) { this.changeBgTo('bg_A'); }
else if (currentIndex == 1) { this.changeBgTo('bg_B'); }
else if (currentIndex == 2) { this.changeBgTo('bg_C'); }
...


En sachant que le nombre d'index peut-être important... Smiley id

Merci d'avance pour votre aide.
Modérateur

this.changeBgTo('bg_' + 'abcdefghijklmnopqrstuvwxyz'.split('')[currentIndex].toUpperCase() );

Modifié par niuxe (02 Aug 2017 - 16:42)
niuxe a écrit :

this.changeBgTo('bg_' + 'abcdefghijklmnopqrstuvwxyz'.split('')[currentIndex].toUpperCase() );


Pour être plus généraliste (mais la réponse est tout à fait correcte) :

const bgList = ['bg_A', 'bg_B', 'bg_C' /* , ... */ ];
this.changeBgTo(bgList[currentIndex]);
Meilleure solution