JS Reference

JS by Category JS by Alphabet

JavaScript

JS Array JS Boolean JS Classes JS Date JS Error JS Global JS JSON JS Math JS Number JS Operators JS RegExp JS Statements JS String

Window

Window Object Window Console Window History Window Location Window Navigator Window Screen

HTML DOM

DOM Document DOM Element DOM Attributes DOM Events DOM Event Objects DOM HTMLCollection DOM Style
alignContent alignItems alignSelf animation animationDelay animationDirection animationDuration animationFillMode animationIterationCount animationName animationTimingFunction animationPlayState background backgroundAttachment backgroundColor backgroundImage backgroundPosition backgroundRepeat backgroundClip backgroundOrigin backgroundSize backfaceVisibility border borderBottom borderBottomColor borderBottomLeftRadius borderBottomRightRadius borderBottomStyle borderBottomWidth borderCollapse borderColor borderImage borderImageOutset borderImageRepeat borderImageSlice borderImageSource borderImageWidth borderLeft borderLeftColor borderLeftStyle borderLeftWidth borderRadius borderRight borderRightColor borderRightStyle borderRightWidth borderSpacing borderStyle borderTop borderTopColor borderTopLeftRadius borderTopRightRadius borderTopStyle borderTopWidth borderWidth bottom boxShadow boxSizing captionSide caretColor clear clip color columnCount columnFill columnGap columnRule columnRuleColor columnRuleStyle columnRuleWidth columns columnSpan columnWidth counterIncrement counterReset cursor direction display emptyCells filter flex flexBasis flexDirection flexFlow flexGrow flexShrink flexWrap cssFloat font fontFamily fontSize fontStyle fontVariant fontWeight fontSizeAdjust height isolation justifyContent left letterSpacing lineHeight listStyle listStyleImage listStylePosition listStyleType margin marginBottom marginLeft marginRight marginTop maxHeight maxWidth minHeight minWidth objectFit objectPosition opacity order orphans outline outlineColor outlineOffset outlineStyle outlineWidth overflow overflowX overflowY padding paddingBottom paddingLeft paddingRight paddingTop pageBreakAfter pageBreakBefore pageBreakInside perspective perspectiveOrigin position quotes resize right scrollBehavior tableLayout tabSize textAlign textAlignLast textDecoration textDecorationColor textDecorationLine textDecorationStyle textIndent textOverflow textShadow textTransform top transform transformOrigin transformStyle transition transitionProperty transitionDuration transitionTimingFunction transitionDelay unicodeBidi userSelect verticalAlign visibility width wordBreak wordSpacing wordWrap widows zIndex

Web APIs

API Console API Fullscreen API Geolocation API History API MediaQueryList API Storage

HTML Objects

<a> <abbr> <address> <area> <article> <aside> <audio> <b> <base> <bdo> <blockquote> <body> <br> <button> <canvas> <caption> <cite> <code> <col> <colgroup> <datalist> <dd> <del> <details> <dfn> <dialog> <div> <dl> <dt> <em> <embed> <fieldset> <figcaption> <figure> <footer> <form> <head> <header> <h1> - <h6> <hr> <html> <i> <iframe> <img> <ins> <input> button <input> checkbox <input> color <input> date <input> datetime <input> datetime-local <input> email <input> file <input> hidden <input> image <input> month <input> number <input> password <input> radio <input> range <input> reset <input> search <input> submit <input> text <input> time <input> url <input> week <kbd> <label> <legend> <li> <link> <map> <mark> <menu> <menuitem> <meta> <meter> <nav> <object> <ol> <optgroup> <option> <output> <p> <param> <pre> <progress> <q> <s> <samp> <script> <section> <select> <small> <source> <span> <strong> <style> <sub> <summary> <sup> <table> <tbody> <td> <tfoot> <th> <thead> <tr> <textarea> <time> <title> <track> <u> <ul> <var> <video>

Other References

CSSStyleDeclaration JS Conversion


Instrução de troca de JavaScript

Exemplo

Execute um bloco de código com base na entrada do usuário:

var text;
var fruits = document.getElementById("myInput").value;

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...";
}

Mais exemplos de "Experimente você mesmo" abaixo.


Definição e uso

A instrução switch executa um bloco de código dependendo dos diferentes casos.

A instrução switch faz parte das Declarações "Condicionais" do JavaScript, que são usadas para executar diferentes ações com base em diferentes condições. Use switch para selecionar um dos muitos blocos de código a serem executados. Esta é a solução perfeita para instruções if/else longas e aninhadas .

A instrução switch avalia uma expressão. O valor da expressão é então comparado com os valores de cada caso na estrutura. Se houver uma correspondência, o bloco de código associado será executado.

A instrução switch é frequentemente usada em conjunto com um break ou uma palavra-chave padrão (ou ambas). Ambos são opcionais:

A palavra-chave break sai do bloco switch. Isso interromperá a execução de mais execução de código e/ou teste de caso dentro do bloco. Se break for omitido, o próximo bloco de código na instrução switch será executado.

A palavra-chave padrão especifica algum código a ser executado se não houver correspondência entre maiúsculas e minúsculas. Só pode haver uma palavra-chave padrão em um switch. Embora seja opcional, é recomendável que você o utilize, pois trata de casos inesperados.


Sintaxe

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

Valores de parâmetro

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


Mais exemplos

Exemplo

Use o número do dia da semana de hoje para calcular o nome do dia da semana (domingo=0, segunda-feira=1, terça-feira=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";
}

Exemplo

Se hoje não for sábado nem domingo, escreva uma mensagem padrão:

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";
}

Exemplo

Às vezes, você desejará que casos diferentes usem o mesmo código, ou caiam em um padrão comum.

Observe que neste exemplo, os casos compartilham o mesmo bloco de código, e que o caso padrão não precisa ser o último caso em um bloco de comutação (no entanto, se o padrão NÃO for o último caso no bloco de comutação, lembre-se de terminá-lo com uma pausa).

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";
}

Exemplo

Usando a instrução switch para executar um bloco de código com base na entrada do usuário, a partir de uma caixa de prompt:

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..";
}

Páginas relacionadas

Tutorial JavaScript: Instruções JavaScript If...Else

Tutorial JavaScript: Instrução de troca de JavaScript

Referência JavaScript: JavaScript instrução if/else

Referência JavaScript: Instrução de quebra de JavaScript


Suporte ao navegador

switch é um recurso ECMAScript1 (ES1).

ES1 (JavaScript 1997) é totalmente suportado em todos os navegadores:

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