解释 JavaScript switch 语句中的严格比较?
JavaScript switch 语句仅使用严格比较 (===),并且不会转换为类型,如果使用严格比较找不到匹配项,将立即执行 default 语句。
以下是 JavaScript switch 语句中严格比较的代码 −
示例
<!DOCTYPE html> <html lang="en" > <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } .result { font-size: 20px; font-weight: 500; } </style> </head> <body> <h1>JavaScript Switch statement strict comparison</h1> Enter day 1-7<input type="text" class="day" /><button class="Btn"> CHECK </button> <div style="color: green;" class="result"></div> <h3> Click on the above button to check if switch performs strict comparison or not </h3> <script> let dayVal = document.querySelector(".day"); let resEle = document.querySelector(".result"); document.querySelector(".Btn").addEventListener("click", () => { switch (dayVal.value) { case 1: resEle.innerHTML = "It's monday"; break; case 2: resEle.innerHTML = "It's tuesday"; break; case 3: resEle.innerHTML = "It's wednesday"; break; case 4: resEle.innerHTML = "It's thursday"; break; case 5: resEle.innerHTML = "It's friday"; break; case 6: resEle.innerHTML = "It's saturday"; break; case 7: resEle.innerHTML = "It's sunday"; break; default: resEle.innerHTML = "Enter a value between 1 - 7"; break; } }); </script> </body> </html>
输出
以上代码将产生以下输出 −
输入数字并单击“检查”时,由于 switch 总会执行严格比较,因此每次都会调用 default 语句 −
广告