logo

Інструкція TypeScript Switch

Інструкція TypeScript switch виконує одну інструкцію з кількох умов. Він обчислює вираз на основі його значення, яке може бути логічним, числом, байтом, коротким, цілим, довгим, типом enum, рядком тощо. Інструкція switch має один блок коду, що відповідає кожному значенню. Коли збіг знайдено, буде виконано відповідний блок. Інструкція switch працює як інструкція сходів if-else-if.

Слід пам’ятати наступні моменти в операторі switch:

  • У операторі switch може бути N випадків.
  • Значення регістру мають бути унікальними.
  • Регістр значень має бути постійним.
  • Кожен оператор case має оператор break у кінці коду. Інструкція break необов'язкова.
  • Оператор switch має блок за замовчуванням, який записується в кінці. Інструкція за замовчуванням необов'язкова.

Синтаксис

 switch(expression){ case expression1: //code to be executed; break; //optional case expression2: //code to be executed; break; //optional ........ default: //when no case is matched, this block will be executed; break; //optional } 

Оператор switch містить такі речі. У операторі switch може бути будь-яка кількість випадків.

Справа: Після регістру має стояти лише одна константа, а потім крапка з комою. Він не може приймати іншу змінну чи вираз.

Перерва: Перерву слід записати в кінці блоку, щоб вийти з оператора switch після виконання блоку case. Якщо ми не пишемо break, виконання продовжується зі значенням, яке відповідає наступному блоку case.

за замовчуванням: Блок за замовчуванням слід записати в кінці оператора switch. Він виконується, коли немає відповідного регістру.

Інструкція TypeScript Switch

приклад

 let a = 3; let b = 2; switch (a+b){ case 1: { console.log('a+b is 1.'); break; } case 2: { console.log('a+b is 5.'); break; } case 3: { console.log('a+b is 6.'); break; } default: { console.log('a+b is 5.'); break; } } 

Вихід:

Інструкція TypeScript Switch

Змінити регістр за допомогою String

 let grade: string = 'A'; switch (grade) { case'A+': console.log('Marks >= 90'+'
&apos;+&apos;Excellent&apos;); break; case&apos;A&apos;: console.log(&apos;Marks [ &gt;= 80 and = 70 and = 60 and <70 ]'+'
'+'average'); break; case'c': console.log('marks < 60'+'
'+'below average'); default: console.log('invalid grade.'); } pre> <p>In this example, we have a string variable grade. The switch statement evaluates grade variable value and match with case clauses and then execute its associated statements.</p> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/typescript-tutorial/79/typescript-switch-statement-3.webp" alt="TypeScript Switch Statement"> <hr> <h2>Switch Case with Enum</h2> <p>In TypeScript, we can use the switch case with Enum in the following ways.</p> <h3>Example</h3> <pre> enum Direction { East, West, North, South }; var dir: Direction = Direction.North; function getDirection() { switch (dir) { case Direction.North: console.log(&apos;You are in North Direction&apos;); break; case Direction.East: console.log(&apos;You are in East Direction&apos;); break; case Direction.South: console.log(&apos;You are in South Direction&apos;); break; case Direction.West: console.log(&apos;You are in West Direction&apos;); break; } } getDirection(); </pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/typescript-tutorial/79/typescript-switch-statement-4.webp" alt="TypeScript Switch Statement"> <hr> <h2>TypeScript Switch Statement is fall-through.</h2> <p>The TypeScript switch statement is fall-through. It means if a break statement is not present, then it executes all statements after the first match case.</p> <h3>Example</h3> <pre> let number = 20; switch(number) { //switch cases without break statements case 10: console.log(&apos;10&apos;); case 20: console.log(&apos;20&apos;); case 30: console.log(&apos;30&apos;); default: console.log(&apos;Not in 10, 20 or 30&apos;); } </pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/typescript-tutorial/79/typescript-switch-statement-5.webp" alt="TypeScript Switch Statement"></70>

Вихід:

Інструкція TypeScript Switch

Інструкція TypeScript Switch є наскрізною.

Оператор TypeScript switch є прохідним. Це означає, що якщо оператора break немає, він виконує всі оператори після першого збігу.

приклад

 let number = 20; switch(number) { //switch cases without break statements case 10: console.log(&apos;10&apos;); case 20: console.log(&apos;20&apos;); case 30: console.log(&apos;30&apos;); default: console.log(&apos;Not in 10, 20 or 30&apos;); } 

Вихід:

Інструкція TypeScript Switch