Содержание
- 1 More
- 2 Инструкция switch
- 3 Definition and Usage
- 4 More Examples
- 5 Images
- 6 Non Standard Syntax
- 7 The default Keyword
- 8 JS Tutorial
- 9 JS Tutorial
- 10 JavaScript Type Conversion Table
- 11 JS Учебник
- 12 Naming Conventions
- 13 JavaScript Coding Conventions
- 14 The JavaScript Switch Statement
- 15 JS Tutorial
- 16 The typeof Operator
More
Fullscreen VideoModal BoxesDelete ModalTimelineScroll IndicatorProgress BarsSkill BarRange SlidersTooltipsDisplay Element HoverPopupsCollapsibleCalendarHTML IncludesTo Do ListLoadersStar RatingUser RatingOverlay EffectContact ChipsCardsFlip CardProfile CardProduct CardAlertsCalloutNotesLabelsCirclesStyle HRCouponList GroupList Without BulletsResponsive TextCutout TextGlowing TextFixed FooterSticky ElementEqual HeightClearfixResponsive FloatsSnackbarFullscreen WindowScroll DrawingSmooth ScrollGradient Bg ScrollSticky HeaderShrink Header on ScrollPricing TableParallaxAspect RatioResponsive IframesToggle Like/DislikeToggle Hide/ShowToggle Dark ModeToggle TextToggle ClassAdd ClassRemove ClassActive ClassTree ViewRemove PropertyOffline DetectionFind Hidden ElementRedirect WebpageZoom HoverFlip BoxCenter VerticallyCenter Button in DIVTransition on HoverArrowsShapesDownload LinkFull Height ElementBrowser WindowCustom ScrollbarHide ScrollbarDevice LookContenteditable BorderPlaceholder ColorText Selection ColorBullet ColorVertical LineDividersAnimate IconsCountdown TimerTypewriterComing Soon PageChat MessagesPopup Chat WindowSplit ScreenTestimonialsSection CounterQuotes SlideshowClosable List ItemsTypical Device BreakpointsDraggable HTML ElementJS Media QueriesSyntax HighlighterJS AnimationsGet Iframe Elements
Инструкция switch
Инструкция switch (англ. переключатель) позволяет выбрать, какой из нескольких блоков кода должен быть выполнен, исходя из возможных значений заданного выражения. Каждое из таких значений называется вариантом (case). Инструкция заменяет собой сразу несколько . Она представляет собой более наглядный способ сравнить выражение сразу с несколькими вариантами.
Синтаксис оператора выглядит следующим образом:
- Выполнение инструкции начинается с вычисления выражения n. Его иногда называют тестовым.
- Выполняется проверка на строгое равенство значения тестового выражения n и значений меток в предложениях case (первому значению value1, затем второму value2 и так далее) в порядке их следования в теле инструкции switch.
- Если соответствие установлено – switch начинает выполняться от соответствующей директивы case и далее, до ближайшего break (или до конца switch, если break отсутствует).
- Если совпадения не произошло, то выполняются инструкции default-ветви. Ветвь default не является обязательной, поэтому при ее отсутствии управление передается следующей за инструкцией switch, т.е. тело ее просто пропускается.
Инструкция выполняет немедленный выход из инструкции switch. Она может располагаться в каждом варианте case, но не является обязательной. Если её нет, то выполняется следующая инструкция из блока switch.
Пример работы инструкции switch:
Выполнить код » Скрыть результаты
При отсутствии инструкции break в каком-либо варианте, управление будет передано инструкциям, относящимся к следующим вариантам. При этом остальные проверки на соответствие выражению не будут выполняться. Интерпретатор JavaScript выйдет из инструкции switch, только когда дойдет до её конца или встретит break. Очевидно, это не то, что обычно нужно для решения задачи выбора. Поэтому каждый блок case, как правило, необходимо заканчивать инструкцией Ьreak или return.
Пример без break:
Выполнить код » Скрыть результаты
alert
Для выхода из инструкции switch может использоваться не только break, но также и инструкции return или continue, если switch находится внутри функции или цикла соответственно.
Definition and Usage
The switch statement executes a block of code depending on different cases.
The switch statement is a part of JavaScript’s «Conditional» Statements, which are used to perform different actions based on different conditions. Use switch to select one of many blocks of code to be executed. This is the perfect solution for long, nested if/else statements.
The switch statement evaluates an expression. The value of the expression is then compared with the values of each case in the structure. If there is a match, the associated block of code is executed.
The switch statement is often used together with a break or a default keyword (or both). These are both optional:
The break keyword breaks out of the switch block. This will stop the execution of more execution of code and/or case testing inside the block. If break is omitted, the next code block in the switch statement is executed.
The default keyword specifies some code to run if there is no case match. There can only be one default keyword in a switch. Although this is optional, it is recommended that you use it, as it takes care of unexpected cases.
More Examples
Example
Use today’s weekday number to calculate the weekday name (Sunday=0, Monday=1, Tuesday=2, …):
var day;switch (new Date().getDay()) { case 0: day = «Sunday»; break; case 1: day = «Monday»; break; case 2: day = «Tuesday»; break; case 3: day = «Wednesday»; break; case 4: day = «Thursday»; break; case 5: day = «Friday»; break; case 6: day = «Saturday»; break; default: day = «Unknown Day»; }
Example
If today is neither Saturday nor Sunday, write a default message:
var text;switch (new Date().getDay()) { case 6: text = «Today is Saturday»; break; case 0: text = «Today is Sunday»; break; default: text = «Looking forward to the Weekend»;}
Example
Sometimes you will want different cases to use the same code, or fall-through to a common default.
Note that in this example, the cases share the same code block, and that the default case does not have to be the last case in a switch block (however, if default is NOT the last case in the switch block, remember to end it with a break).
var text;switch (new Date().getDay()) { case 1: case 2: case 3: default: text = «Looking forward to the Weekend»; break; case 4: case 5: text = «Soon it is Weekend»; break; case 0: case 6: text = «It is Weekend»; }
Example
Using the switch statement to execute a block of code based on user input, from a prompt box:
var text;var favDrink = prompt(«What’s your favorite cocktail drink?»); switch(favDrink) { case «Martini»: text = «Excellent choice! Martini is good for your soul.»; break; case «Daiquiri»: text = «Daiquiri is my favorite too!»; break; case «Cosmopolitan»: text = «Really? Are you sure the Cosmopolitan is your favorite?»; break; default: text = «I have never heard of that one..»;}
Images
SlideshowSlideshow GalleryModal ImagesLightboxResponsive Image GridImage GridTab GalleryImage Overlay FadeImage Overlay SlideImage Overlay ZoomImage Overlay TitleImage Overlay IconImage EffectsBlack and White ImageImage TextImage Text BlocksTransparent Image TextFull Page ImageForm on ImageHero ImageBlur Background ImageChange Bg on ScrollSide-by-Side ImagesRounded ImagesAvatar ImagesResponsive ImagesCenter ImagesThumbnailsBorder Around ImageMeet the TeamSticky ImageFlip an ImageShake an ImagePortfolio GalleryPortfolio with FilteringImage ZoomImage Magnifier GlassImage Comparison Slider
Non Standard Syntax
Due to how a switch functions we must include the brackets around the block of our function. Whenever possible in ES6 I attempt to leave the brackets off. This is a fairly standard syntax in ES6, an example of this syntax is below using arrow functions.
// returns `hi {name}`const sayHi = (name) => `Hi ${name}!!`sayHi("Chris") // output: Hi Chris!
Notice there are no brackets! Now to be fair this new syntax only supports the ability to return one value, but in functional programing thats best. Sadly using the switch statement does not allow us to take full advantage of the new ES6 syntax. (booooo!! )
The default Keyword
The keyword specifies the code to run if there is no case match:
Example
The method returns the weekday as a number between 0 and 6.
If today is neither Saturday (6) nor Sunday (0), write a default message:
switch (new Date().getDay()) { case 6: text = «Today is Saturday»; break; case 0: text = «Today is Sunday»; break; default: text = «Looking forward to the Weekend»;}
The result of text will be:
The case does not have to be the last case in a switch block:
Example
switch (new Date().getDay()) { default: text = «Looking forward to the Weekend»; break; case 6: text = «Today is Saturday»; break; case 0: text = «Today is Sunday»; }
If is not the last case in the switch block, remember to end the default case with a break.
JS Tutorial
JS HOMEJS IntroductionJS Where ToJS OutputJS StatementsJS SyntaxJS CommentsJS VariablesJS OperatorsJS ArithmeticJS AssignmentJS Data TypesJS FunctionsJS ObjectsJS EventsJS StringsJS String MethodsJS NumbersJS Number MethodsJS ArraysJS Array MethodsJS Array SortJS Array IterationJS DatesJS Date FormatsJS Date Get MethodsJS Date Set MethodsJS MathJS RandomJS BooleansJS ComparisonsJS ConditionsJS SwitchJS Loop ForJS Loop WhileJS BreakJS Type ConversionJS BitwiseJS RegExpJS ErrorsJS ScopeJS HoistingJS Strict ModeJS this KeywordJS LetJS ConstJS Arrow FunctionJS DebuggingJS Style GuideJS Best PracticesJS MistakesJS PerformanceJS Reserved WordsJS VersionsJS Version ES5JS Version ES6JS JSON
JS Tutorial
JS HOMEJS IntroductionJS Where ToJS OutputJS StatementsJS SyntaxJS CommentsJS VariablesJS OperatorsJS ArithmeticJS AssignmentJS Data TypesJS FunctionsJS ObjectsJS EventsJS StringsJS String MethodsJS NumbersJS Number MethodsJS ArraysJS Array MethodsJS Array SortJS Array IterationJS DatesJS Date FormatsJS Date Get MethodsJS Date Set MethodsJS MathJS RandomJS BooleansJS ComparisonsJS ConditionsJS SwitchJS Loop ForJS Loop WhileJS BreakJS Type ConversionJS BitwiseJS RegExpJS ErrorsJS ScopeJS HoistingJS Strict ModeJS this KeywordJS LetJS ConstJS Arrow FunctionJS DebuggingJS Style GuideJS Best PracticesJS MistakesJS PerformanceJS Reserved WordsJS VersionsJS Version ES5JS Version ES6JS JSON
JavaScript Type Conversion Table
This table shows the result of converting different JavaScript values to Number, String, and Boolean:
OriginalValue | Convertedto Number | Convertedto String | Convertedto Boolean | Try it |
---|---|---|---|---|
false | «false» | false | Try it » | |
true | 1 | «true» | true | Try it » |
«0» | false | Try it » | ||
1 | 1 | «1» | true | Try it » |
«0» | «0» | true | Try it » | |
«000» | «000» | true | Try it » | |
«1» | 1 | «1» | true | Try it » |
NaN | NaN | «NaN» | false | Try it » |
Infinity | Infinity | «Infinity» | true | Try it » |
-Infinity | -Infinity | «-Infinity» | true | Try it » |
«» | «» | false | Try it » | |
«20» | 20 | «20» | true | Try it » |
«twenty» | NaN | «twenty» | true | Try it » |
«» | true | Try it » | ||
20 | «20» | true | Try it » | |
NaN | «10,20» | true | Try it » | |
NaN | «twenty» | true | Try it » | |
NaN | «ten,twenty» | true | Try it » | |
function(){} | NaN | «function(){}» | true | Try it » |
{ } | NaN | «» | true | Try it » |
null | «null» | false | Try it » | |
undefined | NaN | «undefined» | false | Try it » |
Values in quotes indicate string values.
Red values indicate values (some) programmers might not expect.
JS Учебник
JS СтартJS ВведениеJS УстановкаJS ВыводJS ОбъявленияJS СинтаксисJS КомментарииJS ПеременныеJS ОператорыJS АрифметическиеJS ПрисваиваниеJS Типы данныхJS ФункцииJS ОбъектыJS СобытияJS СтрокиJS Методы строкиJS ЧислаJS Методы числаJS МассивыJS Методы массиваJS Сортировка массиваJS Итерация массиваJS ДатыJS Форматы датJS Методы получения датJS Методы установки датJS МатематическиеJS РандомныеJS БулевыJS СравненияJS УсловияJS SwitchJS Цикл ForJS Цикл WhileJS ПрерываниеJS Преобразование типовJS ПобитовыеJS Регулярные выраженияJS ОшибкиJS Область действияJS ПодъёмJS Строгий режимJS Ключевое слово thisJS Ключевое слово LetJS Ключевое слово ConstJS Функции стрелокJS КлассыJS ОтладкаJS Гид по стилюJS Лучшие практикиJS ОшибкиJS ПроизводительностьJS Зарезервированные словаJS ВерсииJS Версия ES5JS Версия ES6JS JSON
Naming Conventions
Always use the same naming convention for all your code. For example:
- Variable and function names written as camelCase
- Global variables written in UPPERCASE (We don’t, but it’s quite common)
- Constants (like PI) written in UPPERCASE
Should you use hyp-hens, camelCase, or under_scores in variable names?
This is a question programmers often discuss. The answer depends on who you ask:
Hyphens in HTML and CSS:
HTML5 attributes can start with data- (data-quantity, data-price).
CSS uses hyphens in property-names (font-size).
Hyphens can be mistaken as subtraction attempts. Hyphens are not allowed in JavaScript names.
Underscores:
Many programmers prefer to use underscores (date_of_birth), especially in SQL databases.
Underscores are often used in PHP documentation.
PascalCase:
PascalCase is often preferred by C programmers.
camelCase:
camelCase is used by JavaScript itself, by jQuery, and other JavaScript libraries.
Do not start names with a $ sign. It will put you in conflict with many JavaScript library names.
JavaScript Coding Conventions
Coding conventions are style guidelines for programming. They typically cover:
- Naming and declaration rules for variables and functions.
- Rules for the use of white space, indentation, and comments.
- Programming practices and principles
Coding conventions secure quality:
- Improves code readability
- Make code maintenance easier
Coding conventions can be documented rules for teams to follow, or just be your individual coding practice.
This page describes the general JavaScript code conventions used by W3Schools. You should also read the next chapter «Best Practices», and learn how to avoid coding pitfalls.
The JavaScript Switch Statement
Use the statement to select one of many code blocks to be executed.
Syntax
switch(expression) { case x: // code block break; case y: // code block break; default: // code block }
This is how it works:
- The switch expression is evaluated once.
- The value of the expression is compared with the values of each case.
- If there is a match, the associated block of code is executed.
- If there is no match, the default code block is executed.
Example
The method returns the weekday as a number between 0 and 6.
(Sunday=0, Monday=1, Tuesday=2 ..)
This example uses the weekday number to calculate the weekday name:
switch (new Date().getDay()) { case 0: day = «Sunday»; break; case 1: day = «Monday»; break; case 2: day = «Tuesday»; break; case 3: day = «Wednesday»; break; case 4: day = «Thursday»; break; case 5: day = «Friday»; break; case 6: day = «Saturday»; }
The result of day will be:
JS Tutorial
JS HOMEJS IntroductionJS Where ToJS OutputJS StatementsJS SyntaxJS CommentsJS VariablesJS OperatorsJS ArithmeticJS AssignmentJS Data TypesJS FunctionsJS ObjectsJS EventsJS StringsJS String MethodsJS NumbersJS Number MethodsJS ArraysJS Array MethodsJS Array SortJS Array IterationJS DatesJS Date FormatsJS Date Get MethodsJS Date Set MethodsJS MathJS RandomJS BooleansJS ComparisonsJS ConditionsJS SwitchJS Loop ForJS Loop WhileJS BreakJS Type ConversionJS BitwiseJS RegExpJS ErrorsJS ScopeJS HoistingJS Strict ModeJS this KeywordJS LetJS ConstJS Arrow FunctionJS DebuggingJS Style GuideJS Best PracticesJS MistakesJS PerformanceJS Reserved WordsJS VersionsJS Version ES5JS Version ES6JS JSON
The typeof Operator
You can use the operator to find the data type of a JavaScript variable.
Example
typeof «John» // Returns «string» typeof 3.14 // Returns «number» typeof NaN // Returns «number» typeof false // Returns «boolean» typeof // Returns «object» typeof {name:’John’, age:34} // Returns «object»typeof new Date() // Returns «object»typeof function () {} // Returns «function» typeof myCar // Returns «undefined» * typeof null // Returns «object»
Please observe:
- The data type of NaN is number
- The data type of an array is object
- The data type of a date is object
- The data type of null is object
- The data type of an undefined variable is undefined *
- The data type of a variable that has not been assigned a value is also undefined *
You cannot use to determine if a JavaScript object is an array (or a date).
С этим читают