Conditional Operator for else if?
Copy link to clipboard
Copied
I used the google compiler on one of my scripts. It worked fine except I am getting hung up on some of the conditional statements it made. Originally I had a series of if else if statements. When changed to Conditional Operator it changes the fuctionality of it. Here we go if anyone can help I will take any tips.
My version:
if(myYear.selection.text=="10"){yearSelect=0;}
else if(myYear.selection.text=="11"){yearSelect=1;}
else if(myYear.selection.text=="12"){yearSelect=2;}
else if(myYear.selection.text=="13"){yearSelect=3;}
else if(myYear.selection.text=="14"){yearSelect=4;}
else{yearSelect=5;}
Google version:
yearSelect="10"==b.selection.text?0:"11"==b.selection.text?1:"12"==b.selection.text?2:"13"==b.selection.text?3:"14"==b.selection.text?4:5,
Thanks in advance for any advice.
Brett.
Copy link to clipboard
Copied
Common Javascript syntax.
a = b ? c : d;
is equal to
if (b == true)
a = c;
else
a = d;
What does "it changes the fuctionality of it" mean? Doesn't it work anymore?
Copy link to clipboard
Copied
.. Apart from that, there is no need for your original long list of "if .. else". For a list of possible inputs, you should consider something like this:
switch(myYear.selection.text)
{
case "10": yearSelect=0; break;
case "11": yearSelect=1; break;
case "12": yearSelect=2; break;
case "13": yearSelect=3; break;
case "14": yearSelect=4; break;
default: yearSelect=5;
}
or, with your input and output, something as simple as
yearSelect = Number(myYear.selection.text)-10;
-- but I don't know what your possible range of inputs is. If it's "anything goes", you have to check for a not-in-range and then set it to your default of 5.
Copy link to clipboard
Copied
I just tried this and it worked thanks you for your help!
yearSelect = yearSelect="10"==b.selection.text?0:
yearSelect="11"==b.selection.text?1:
yearSelect="12"==b.selection.text?2:
yearSelect="13"==b.selection.text?3:
yearSelect="14"==b.selection.text?4:
5,
I will also consider the switch. Thank you.
Copy link to clipboard
Copied
Brett,
The difference between Jongware's version and your last one is that Jongware's version is easy to understand, while your last version is not. Why would you entertain such a braintwister when there's such a clear method available? that Google comes up with those constructions doesn't mean much.
Peter
Copy link to clipboard
Copied
Thanks Peter. Very good to have your perspective.

