简体   繁体   中英

Condensing multiple if statements in JavaScript

I have this:

if(currentSlide !== 3) {
    $('#chapterBackground.intro').fadeOut(100);
}

if(currentSlide !== 4) {
    $('#chapterBackground.intro').fadeOut(100);
}

...and want to essentially say if currentSlide is neither 3 OR 4, then perform the fadeOut function.

if((currentSlide !== 3) || (currentSlide !== 4))  {
    $('#chapterBackground.intro').fadeOut(100);
}

Apologies, edited.

You can use the OR operator within a single if condition:

if(currentSlide !==3 || currentSlide !==4) {
    $('#chapterBackground.intro').fadeOut(100);
}

Here you go:

if(currentSlide !== 3 || currentSlide !== 4) {
    $('#chapterBackground.intro').fadeOut(100);
}

The || means "OR". For "AND" you would use the && operator ;)

if(currentSlide !== 3 || currentSlide !== 4) {
    $('#chapterBackground.intro').fadeOut(100);
}

And here goes mine:

if ( currentSlide + 1 >> 1 != 1 )

:D

Just one of many options:

currentSlide = 3;

//The number would match the slide you want the transition to occur at
//So at slide 3 I want the intro to fade out
var slideIndexes = {
        3 : function() { $('#chapterBackground.intro').fadeOut(100); },
        16 : function() { $('#chapterBackground.presentation').fadeOut(100); },
        20 : function () { $('#chapterBackground.credits').fadeOut(100); }
};

if (slideIndexes[currentSlide]) slideIndexes[currentSlide]();

And a beautiful jsfiddle to accompany this code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM