PDA

View Full Version : Changing If statement to switch



kayut
03-08-2017, 09:31 AM
Hi,

I'm trying to change this if statement to a switch like this:

Before



if ($(this).attr('id') === 'right') {
if (tabindex === slides) {
tabindex = 1;
move = '+=' + windowWidth * (slides - 1);
} else {
tabindex += 1;
move = '-=' + windowWidth;
}
} else {
if (tabindex === 1) {
tabindex = slides;
move = '-=' + windowWidth * (slides - 1);
} else {
tabindex -= 1;
move = '+=' + windowWidth;
}
}


After



if ($(this).attr('id') === 'right') {

switch (tabindex) {
case (tabindex === slides):
tabindex = 1;
move = '+=' + windowWidth * (slides - 1);
break;
default:
tabindex += 1;
move = '-=' + windowWidth;
}

} else {
switch (tabindex) {
case (tabindex === 1):
tabindex = slides;
move = '-=' + windowWidth * (slides - 1);
break;
default:
tabindex -= 1;
move = '+=' + windowWidth;
}


But the result is not the same.
What am I doing wrong? What is the right solution?

Thanks

jscheuer1
03-08-2017, 02:29 PM
You're putting too much code into the first line of the case statements. Those need to be (or evaluate to) single values which are automatically compared to the value being switched. See also:

https://www.w3schools.com/js/js_switch.asp

This works in the console:


if ($(this).attr('id') === 'right') {
switch(tabindex){
case slides:
tabindex = 1;
move = '+=' + windowWidth * (slides - 1);
break;
default:
tabindex += 1;
move = '-=' + windowWidth;
}
} else {
switch(tabindex){
case 1:
tabindex = slides;
move = '-=' + windowWidth * (slides - 1);
break;
default:
tabindex -= 1;
move = '+=' + windowWidth;
}
}