The switch construct replaces several if once.
This is a more visual way of comparing an expression with several options at once.
Syntax
It looks like this:
Work example
An example of using a switch (the code that worked is highlighted):
Only one value will be displayed corresponding to 4 . After that break will abort execution.
If it is not interrupted, it will go further, while the remaining checks are ignored.
For example:
In the example above, three alert be executed in sequence.
alert( 'Я таких значений не знаю' ); |
In case can be any expressions , including variables and functions.
For example:
case grouping
Multiple case values can be grouped.
In the example below, case 3 and case 5 execute the same code:
With case 3 execution goes from line (3) and goes down to the nearest break , thus passing what is intended for case 5 .
Importance: 5
If the condition is strictly followed, the comparison should be strict '===' .
In the real case, the usual comparison is likely to be '==' .
1 | if (browser == 'IE' ) { |
2 | alert( 'О, да у вас IE!' ); |
3 | } else if (browser == 'Chrome' || browser == 'Firefox' |
4 | || browser == || browser == 'Safari' || browser == || browser == 'Opera' ) { |
5 | alert( 'Да, и эти браузеры мы поддерживаем' ); |
7 | alert( 'Мы надеемся, что и в вашем браузере все ок!' ); |
As you can see, this record is much worse read than the switch construction.
[Open task in new window]
Type matters
The following example takes value from the visitor.
What will it display when entering numbers 0, 1, 2, 3? Think and read on ...
- If you enter
0 or 1 first alert will be executed, then the execution will continue down to the first break and output the second alert('Два') . - If you enter
2 , switch goes to case '2' and prints Два . - When you enter
3 , switch switches to default . This is because the prompt returns the string '3' , not a number. Types are different. Switch uses strict equality === , so there will be no coincidence. - When canceled,
case null will work.
Importance: 4
The first two checks are the usual case , the third is divided into two case :
Pay attention: break below is not obligatory, but is set according to the “rules of good form”.
If it is not worth it, then when adding a new case to the end, for example case 4 , we will most likely forget to put it. As a result, the execution of case 2 / case 3 will continue on case 4 and there will be an error.
Comments
To leave a comment
Scripting client side JavaScript, jqvery, BackBone
Terms: Scripting client side JavaScript, jqvery, BackBone