JavaScript 对字符串进行 switch 操作
switch-case
语句与 conditional
语句相同。这两个函数之间的区别仅在于语法。
switch
语句计算表达式及其类型,然后将其与声明性 case
子句匹配。匹配是通过 ===
严格相等操作来操作的。
triple equal ===
只会推断出在类型和案例中是可靠的匹配。这只会产生布尔值,因此我们的子句要么匹配 switch 表达式,要么跟随 default
部分。
用 switch
字符串满足 case
子句
我们将使用 string
启动一个变量,并将此表达式传递给此示例的 switch
语句。接下来,switch
语句将比较 case
子句和它拥有的表达式。
如果匹配返回 true
,则该特定代码块的代码行将运行。
代码片段:
var str = 'butter';
switch (str) {
case 'butter':
console.log('Buttery delicious!');
break;
case 'chocolate':
console.log('Ain\'t chocolate everyones fav!');
break;
default:
console.log('What\'s wrong with your tastebud?');
}
通过 switch
中的类型转换字符串表达式满足 case
子句
我们将创建一个带有数字
的变量,但是当我们将它作为 switch
语句的表达式传递时,我们将执行类型转换
。
如果 switch
语句表达式和 case
子句的显式条件是相同的数据类型,则它不会适用于 default
情况。
如果你不知道表达式的类型,请尝试将其转换为 string
或针对特定情况的任何其他首选类型。通常在开发中,你可能会遇到 this
对象实例,当你跟随 switch(this)
时,你可能会遇到错误。
即使它是一个实例,它也不同于字符串原语。因此,你必须以这种方式明确定义它:switch(String(this))
。
代码片段:
var val = 42;
switch (String(val)) {
case 1:
case 2:
case 3:
case 42:
console.log('It\'s a digit');
break;
default:
console.log('OOPS! This is string');
}
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
用 jQuery 检查复选框是否被选中
发布时间:2024/03/24 浏览次数:102 分类:JavaScript
-
在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的
jQuery 中的 Window.onload 与 $(document).ready
发布时间:2024/03/24 浏览次数:180 分类:JavaScript
-
本教程演示了如何在 jQuery 中使用 Window.onload 和 $(document).ready 事件。