两者有什么区别:
switch (expression) {
case:
somethings;
break;
}
和
switch (expression) {
case: {
somethings;
break;
}
}
起初我以为我可以像这样返回一个对象字面量,但事实证明这是一个语法错误.到底有什么区别?
At first I thought that I could return an object literal like so, but it turns out it's a syntax error. What's the difference actually?
另一个问题的例子:如何将switch语句传递为Javascript ES6 中的函数参数?
这种方式使用的花括号建立了自己的块作用域,可以在其中定义局部let
变量或const
常量:
Curly braces used in this way establish their own block scope, in which you can define local let
variables or const
constants:
switch (false) {
case true: {
let x = "bar";
console.log(x);
break;
}
case false: {
let x = "baz";
console.log(x);
break;
}
}
该示例将在没有嵌套块范围的情况下抛出,因为在 Ecmascript 2015 的同一范围内不允许使用相同标识符的多个 let
/const
声明.
The example would throw without nested block scopes, since multiple let
/const
declarations with the same identifier are not allowed within the same scope in Ecmascript 2015.
请注意 switch
语句本身创建了一个块作用域,即无论你是否使用嵌套块作用域,let
/const
声明switch
内部不要泄漏到父作用域中.
Please note that the switch
statement creates a block scope itself, i.e. whether you use nested block scopes or not, let
/const
declarations inside switch
don't leak into the parent scope.
但是,在 switch
的上下文中,大括号也纯粹用于装饰,以在视觉上突出各个 case
分支的块.
However, in the context of switch
, curly brackets are also used purely decorative, to visually highlight the blocks of the individual case
branches.
这篇关于es6 中的 case 之后的 switch 语句中的花括号有什么作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!