Case with string javascript

JavaScript switch Statement

switch(fruits) case «Banana»:
text = «Banana is good!»;
break;
case «Orange»:
text = «I am not a fan of orange.»;
break;
case «Apple»:
text = «How you like them apples?»;
break;
default:
text = «I have never heard of that fruit. «;
>

More «Try it Yourself» examples below.

Description

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.

Читайте также:  For key value list python

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.

Syntax

switch(expression) case n:
code block
break;
case n:
code block
break;
default:
default code block
>

Parameter Values

Parameter Description
expression Required. Specifies an expression to be evaluated. The expression is evaluated once. The value of the expression is compared with the values of each case labels in the structure. If there is a match, the associated block of code is executed

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..»;
>

Browser Support

switch is an ECMAScript1 (ES1) feature.

ES1 (JavaScript 1997) is fully supported in all browsers:

Chrome Edge Firefox Safari Opera IE
Yes Yes Yes Yes Yes Yes

Источник

Конструкция «switch»

Конструкция switch заменяет собой сразу несколько if .

Она представляет собой более наглядный способ сравнить выражение сразу с несколькими вариантами.

Синтаксис

Конструкция switch имеет один или более блок case и необязательный блок default .

  • Переменная x проверяется на строгое равенство первому значению value1 , затем второму value2 и так далее.
  • Если соответствие установлено – switch начинает выполняться от соответствующей директивы case и далее, до ближайшего break (или до конца switch ).
  • Если ни один case не совпал – выполняется (если есть) вариант default .

Пример работы

Пример использования switch (сработавший код выделен):

Здесь оператор switch последовательно сравнит a со всеми вариантами из case .

Сначала 3 , затем – так как нет совпадения – 4 . Совпадение найдено, будет выполнен этот вариант, со строки alert( ‘В точку!’ ) и далее, до ближайшего break , который прервёт выполнение.

Если break нет, то выполнение пойдёт ниже по следующим case , при этом остальные проверки игнорируются.

В примере выше последовательно выполнятся три alert :

alert( 'В точку!' ); alert( 'Перебор' ); alert( "Нет таких значений" );

И switch и case допускают любое выражение в качестве аргумента.

let a = "1"; let b = 0; switch (+a)

В этом примере выражение +a вычисляется в 1 , что совпадает с выражением b + 1 в case , и следовательно, код в этом блоке будет выполнен.

Группировка «case»

Несколько вариантов case , использующих один код, можно группировать.

Для примера, выполним один и тот же код для case 3 и case 5 , сгруппировав их:

Теперь оба варианта 3 и 5 выводят одно сообщение.

Возможность группировать case – это побочный эффект того, как switch/case работает без break . Здесь выполнение case 3 начинается со строки (*) и продолжается в case 5 , потому что отсутствует break .

Тип имеет значение

Нужно отметить, что проверка на равенство всегда строгая. Значения должны быть одного типа, чтобы выполнялось равенство.

Для примера, давайте рассмотрим следующий код:

let arg = prompt("Введите число?"); switch (arg)
  1. Для ‘0’ и ‘1’ выполнится первый alert .
  2. Для ‘2’ – второй alert .
  3. Но для 3 , результат выполнения prompt будет строка «3» , которая не соответствует строгому равенству === с числом 3 . Таким образом, мы имеем «мёртвый код» в case 3 ! Выполнится вариант default .

Задачи

Напишите «if», аналогичный «switch»

Напишите if..else , соответствующий следующему switch :

Если совсем точно следовать работе switch , то if должен выполнять строгое сравнение ‘===’ .

Впрочем, для таких строк, подойдёт и обычное сравнение ‘==’ .

if(browser == 'Edge') < alert("You've got the Edge!"); >else if (browser == 'Chrome' || browser == 'Firefox' || browser == 'Safari' || browser == 'Opera') < alert( 'Okay we support these browsers too' ); >else

Обратите внимание: конструкция browser == ‘Chrome’ || browser == ‘Firefox’ . разбита на несколько строк для лучшей читаемости.

Но всё равно запись через switch нагляднее.

Источник

Js switch statements with string and multiple case

the reason it works is probably that the case expression evaluated is interpreted as a true or false value and then checked against the main — switch(true) Solution 2: You can’t the case need to single value, that’s compared to switch expression, but you can put multiple cases to execute the same code: but in order to use test as case you can pass true to switch (I found that trick in some open source project): but this is the same as Solution 3: Note: you’re using incorrectly, it’s a method of a regex object, so you need rather than . A switch statement using multiple value cases correspond to using more than one value in a single case.

Replacing multiple parts of a string with switch cases js

Replace returns a new string; it does not replace the value in the string you call it on. Maybe what you want is another string variable that you modify and then return, like so:

function convertText(str) < let result = str; for (let el of str) < switch(el) < case "&": result = result.replace("&","on"); // you may want another break here, unless fall-through is your desired behavior case "G": result = result.replace("G","key"); break; >> return result; > console.log(convertText("D&G")); 

You are still using replace . But you could take a new string and add the value if a cetain character is found or add the actual character to the result.

function convertText(str) < let result = ''; for (let el of str) < switch (el) < case "&": result += "on"; break; case "G": result += "key" break; default: result += el; >> return result; >console.log(convertText("D&G"));

When using a switch statement in Javascript with multiple cases, how can I refer to a case?

Just use additional arguments to log and Animal .

console.log('This', Animal, 'will go on Noah\'s Ark.'); 

You could use a token %s ( string in this case) and than after a comma use your variable:

var Animal = 'Giraffe'; switch (Animal)
var Animal = 'Giraffe'; switch (Animal)

(note: I’m using string concatenation here under the assumption that you may actually want to do something other than use the console.log function to do something like this — if you really just want to use console.log , it may be more reasonable to use one of the other answers provided)

Can I use a case/switch statement with two variables?, Second, the only way to use switch with multiple variables is to combine them into one primitive (string, number, etc) value:

Switch combining cases string regex and number

OK, compiling both answers above my code that worked and was most elegant IMO is:

var fieldVal = $(this).val(); var msg; switch (true) < case /Yes/.test(fieldVal): msg = "FOO"; break; case fieldVal >10 : msg = "BAR"; break; > 

this works as separate if statements since we are evaluating whether or not the case returns true but in a clearer and more concise way that could give us the option to add totally disparate test statements in one switch.

the reason it works is probably that the case expression evaluated is interpreted as a true or false value and then checked against the main — switch(true)

You can’t the case need to single value, that’s compared to switch expression, but you can put multiple cases to execute the same code:

but in order to use test as case you can pass true to switch (I found that trick in some open source project):

but this is the same as if/else

Note: you’re using test() incorrectly, it’s a method of a regex object, so you need /Yes/.test(field) rather than field.test(‘Yes’) . Anyway.

If you’ve only got two cases as shown then I’d use an if/else/else if structure:

var field = $(this).val(); var msg; if(/Yes/.test(field)) < msg = "FOO\n"; >else if (field === 10)

If you need to add additional cases I’d just add extra if else <> branches on the end.

If you have several specific numeric cases you might consider putting them in a switch with the regex tests in a default at the end:

The switch (true) option you alluded to in the question is really just a messier version of an if/else/else if , so it doesn’t really make sense unless you have some fall-through cases:

switch(true) case /Yes/.test(field): case /Y/.text(field): case /Whatever/.text(field): msg = "FOO\n"; break; case field == 10: msg = "BAR\n"; break; > 

. and even then an if with multiple conditions joined by || arguably just as tidy with appropriate newlines, and combining multiple regexes into a single one is probably a lot neater.

Switch statement for multiple cases in JavaScript, In Javascript to assign multiple cases in a switch, we have to define different case without break inbetween like given below:

Golang program that uses switch, multiple value cases

Switch statement is a multiway branching which provides an alternative way too lengthy if-else comparisons. It selects a single block to be executed from a listing of multiple blocks on the basis of the value of an expression or state of a single variable. A switch statement using multiple value cases correspond to using more than one value in a single case. This is achieved by separating the multiple values in the case with a comma.

Источник

Оцените статью