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


Tuyên bố chuyển đổi JavaScript

Thí dụ

Thực thi một khối mã dựa trên đầu vào của người dùng:

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

Thêm các ví dụ "Hãy tự mình thử" bên dưới.


Định nghĩa và Cách sử dụng

Câu lệnh switch thực thi một khối mã tùy thuộc vào các trường hợp khác nhau.

Câu lệnh switch là một phần của Câu lệnh "Điều kiện" của JavaScript, được sử dụng để thực hiện các hành động khác nhau dựa trên các điều kiện khác nhau. Sử dụng công tắc để chọn một trong nhiều khối mã sẽ được thực thi. Đây là giải pháp hoàn hảo cho các câu lệnh if / else dài, lồng nhau .

Câu lệnh switch đánh giá một biểu thức. Giá trị của biểu thức sau đó được so sánh với giá trị của từng trường hợp trong cấu trúc. Nếu có sự trùng khớp, khối mã được liên kết sẽ được thực thi.

Câu lệnh switch thường được sử dụng cùng với ngắt hoặc từ khóa mặc định (hoặc cả hai). Cả hai đều là tùy chọn:

Từ khóa break thoát ra khỏi khối chuyển đổi. Điều này sẽ dừng việc thực thi thêm mã và / hoặc kiểm thử trường hợp bên trong khối. Nếu ngắt được bỏ qua, khối mã tiếp theo trong câu lệnh switch sẽ được thực thi.

Từ khóa mặc định chỉ định một số mã để chạy nếu không có đối sánh chữ hoa chữ thường. Chỉ có thể có một từ khóa mặc định trong một công tắc. Mặc dù điều này là tùy chọn, nhưng bạn nên sử dụng nó, vì nó đề phòng các trường hợp không mong muốn.


Cú pháp

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

Giá trị tham số

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


Các ví dụ khác

Thí dụ

Sử dụng số ngày trong tuần hôm nay để tính tên ngày trong tuần (Chủ nhật = 0, Thứ Hai = 1, Thứ Ba = 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";
}

Thí dụ

Nếu hôm nay không phải thứ bảy cũng không phải chủ nhật, hãy viết một tin nhắn mặc định:

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

Thí dụ

Đôi khi bạn sẽ muốn các trường hợp khác nhau sử dụng cùng một mã hoặc chuyển sang một mặc định chung.

Lưu ý rằng trong ví dụ này, các trường hợp chia sẻ cùng một khối mã và trường hợp mặc định không nhất thiết phải là trường hợp cuối cùng trong một khối chuyển đổi (tuy nhiên, nếu mặc định KHÔNG phải là trường hợp cuối cùng trong khối chuyển đổi, hãy nhớ kết thúc nó với một thời gian nghỉ).

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

Thí dụ

Sử dụng câu lệnh switch để thực thi một khối mã dựa trên đầu vào của người dùng, từ một hộp nhắc:

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

Các trang liên quan

Hướng dẫn JavaScript: JavaScript If ... Các câu lệnh khác

Hướng dẫn JavaScript: Tuyên bố chuyển đổi JavaScript

Tham khảo JavaScript: Câu lệnh JavaScript if / else

Tham khảo JavaScript: Tuyên bố ngắt JavaScript


Hỗ trợ trình duyệt

switch là một tính năng ECMAScript1 (ES1).

ES1 (JavaScript 1997) được hỗ trợ đầy đủ trong tất cả các trình duyệt:

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