Полное руководство по switch-выражениям в java 12
Содержание:
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
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).
Object Rules
General rules for object definitions:
- Place the opening bracket on the same line as the object name.
- Use colon plus one space between each property and its value.
- Use quotes around string values, not around numeric values.
- Do not add a comma after the last property-value pair.
- Place the closing bracket on a new line, without
leading spaces. - Always end an object definition with a semicolon.
Example
var person = { firstName: «John»,
lastName: «Doe», age: 50, eyeColor:
«blue»};
Short objects can be written compressed, on one line, using spaces only
between properties, like this:
var person = {firstName:»John», lastName:»Doe», age:50, eyeColor:»blue»};
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.
Converting Dates to Strings
The global method can convert dates to
strings.
String(Date()) // returns «Thu Jul 17 2014 15:38:19 GMT+0200 (W. Europe Daylight Time)»
The Date method does the same.
Example
Date().toString() // returns «Thu Jul 17 2014 15:38:19 GMT+0200 (W. Europe Daylight Time)»
In the chapter Date Methods, you
will find more methods that can be used to convert dates to
strings:
| Method | Description |
|---|---|
| getDate() | Get the day as a number (1-31) |
| getDay() | Get the weekday a number (0-6) |
| getFullYear() | Get the four digit year (yyyy) |
| getHours() | Get the hour (0-23) |
| getMilliseconds() | Get the milliseconds (0-999) |
| getMinutes() | Get the minutes (0-59) |
| getMonth() | Get the month (0-11) |
| getSeconds() | Get the seconds (0-59) |
| getTime() | Get the time (milliseconds since January 1, 1970) |
Инструкция 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 находится внутри функции или цикла соответственно.
JavaScript оператор Switch
Используйте оператор чтобы выбрать один из множества блоков кода для выполнения.
Синтаксис
switch(выражение) {
case x: // блок кода break;
case y: // блок кода break;
default:
// блок кода
}
Вот как это работает:
- Выражение switch (переключателя) вычисляется один раз.
- Значение выражения сравнивается со значениями каждого кейса.
- Если есть совпадение, соответствующий блок кода выполняется.
Пример
Метод возвращает день недели в виде числа от 0 до 6.
(Воскресенье=0, Понедельник=1, Вторник=2 ..)
В этом примере номер дня недели используется для вычисления названия дня недели:
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 constructor Property
The property returns the constructor
function for all JavaScript variables.
«John».constructor
// Returns function String() {}
(3.14).constructor
// Returns function Number() {}
false.constructor // Returns
function Boolean() {}
.constructor
// Returns function Array() {}
{name:’John’,age:34}.constructor
// Returns function Object() {}
new Date().constructor
// Returns function Date() {}
function () {}.constructor // Returns
function Function(){}
You can check the constructor property to find out if an object is an
(contains the word «Array»):
function isArray(myArray) {
return myArray.constructor.toString().indexOf(«Array») > -1;
}
Or even simpler, you can check if the object is an Array function:
function isArray(myArray) {
return myArray.constructor
=== Array;
}
You can check the constructor property to find out if an object is a
(contains the word «Date»):
function isDate(myDate) {
return myDate.constructor.toString().indexOf(«Date») > -1;
}
Or even simpler, you can check if the object is a Date function:
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
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!! )
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
Свой итератор
Допустим, у нас есть некий объект, который надо «умным способом» перебрать.
Например, – диапазон чисел от до , и мы хотим, чтобы «перебирал» этот объект. При этом под перебором мы подразумеваем перечисление чисел от до .
Объект без итератора:
Для возможности использовать объект в нужно создать в нём свойство с названием (системный символ).
При вызове метода перебираемый объект должен возвращать другой объект («итератор»), который умеет осуществлять перебор.
По стандарту у такого объекта должен быть метод , который при каждом вызове возвращает очередное значение и проверяет, окончен ли перебор.
В коде это выглядит следующим образом:
Как видно из кода выше, здесь имеет место разделение сущностей:
- Перебираемый объект сам не реализует методы для своего перебора.
- Для этого создаётся другой объект, который хранит текущее состояние перебора и возвращает значение. Этот объект называется итератором и возвращается при вызове метода .
- У итератора должен быть метод , который при каждом вызове возвращает объект со свойствами:
- – очередное значение,
- – равно если есть ещё значения, и – в конце.
Конструкция в начале своего выполнения автоматически вызывает , получает итератор и далее вызывает метод до получения . Такова внутренняя механика. Внешний код при переборе через видит только значения.
Такое отделение функциональности перебора от самого объекта даёт дополнительную гибкость. Например, объект может возвращать разные итераторы в зависимости от своего настроения и времени суток. Однако, бывают ситуации когда оно не нужно.
Если функциональность по перебору (метод ) предоставляется самим объектом, то можно вернуть в качестве итератора:
При таком подходе сам объект и хранит состояние итерации (текущий перебираемый элемент).
В данном случае это работает, но для большей гибкости и понятности кода рекомендуется, всё же, выделять итератор в отдельный объект со своим состоянием и кодом.
Оператор spread и итераторы
В последней строке примера выше можно видеть, что итерируемый объект передаётся через spread для .
При этом интерпретируется как последовательность чисел. То есть произойдёт цикл по , и его результаты будут использованы в качестве списка аргументов.
Бесконечные итераторы
Возможны и бесконечные итераторы. Например, пример выше при будет таковым. Или можно сделать итератор, генерирующий бесконечную последовательность псевдослучайных чисел. Тоже полезно.
Нет никаких ограничений на , он может возвращать всё новые и новые значения, и это нормально.
Разумеется, цикл по такому итератору тоже будет бесконечным, нужно его прерывать, например, через .
A Complex Example
Lets say for example that you are currently using a switch statement for your Redux Store. The following example will show you how to implement your Redux store using an object literal switch.
Redux Store Reducers with Object Literals
I wont go into to much detail on this code as I believe the breakdown of the simple example above explains how this redux store will work. Just note the lack of a switch statement and the increased readability of our code.
Conclusion
The switch statement is a staple of many programing languages but has many inherent problems that can be solved by implementing an object literal solution instead. This does not mean that there are no uses for the switch statement or that object literals is always the right answer. Instead object literals as switches should become another tool in your javascript tool belt.
Thanks!
Thanks for taking the time to read this article! I appreciate and value every recommend, comment (nice or mean), and follow! I’ll be covering more topics in the near future about rewriting basic Javascript concepts using the new standards.
Useful Reading
The following are some useful readings based of off topics covered in this article.
- ES6 In Depth — covers ES6 topics by the guys who implemented it in Firefox!
- Let and Const
- Arrow Functions
- Template Strings
- Switch vs Object Literal Performance
Learning Speed
In this tutorial, the learning speed is your choice.
Everything is up to you.
If you are struggling, take a break, or re-read the material.
Always make sure you understand all the «Try-it-Yourself»
examples.
The only way to become a clever programmer is to:
Practice. Practice. Practice. Code. Code. Code !
Commonly Asked Questions
- How do I get JavaScript?
- Where can I download JavaScript?
- Is JavaScript Free?
You don’t have to get or download JavaScript.
JavaScript is already running in your browser on your computer,
on your tablet, and on your smart-phone.
JavaScript is free to use for everyone.
JavaScript References
W3Schools maintains a complete JavaScript reference, including all HTML and browser objects.
The reference contains examples for all properties, methods and events, and
is continuously updated according to the latest web standards.
Complete JavaScript Reference »
W3Schools’ Online Certification
The perfect solution for professionals who need to balance work, family, and career building.
More than 25 000 certificates already issued!
The HTML Certificate documents your knowledge of HTML.
The CSS Certificate documents your knowledge of advanced CSS.
The JavaScript Certificate documents your knowledge of JavaScript and HTML DOM.
The Python Certificate documents your knowledge of Python.
The jQuery Certificate documents your knowledge of jQuery.
The SQL Certificate documents your knowledge of SQL.
The PHP Certificate documents your knowledge of PHP and MySQL.
The XML Certificate documents your knowledge of XML, XML DOM and XSLT.
The Bootstrap Certificate documents your knowledge of the Bootstrap framework.