es6中的case后在switch语句中花括号有什么作用? [英] What do the curly braces do in switch statement after case in es6?
问题描述
之间有什么区别
switch (expression) {
case:
somethings;
break;
}
和
switch (expression) {
case: {
somethings;
break;
}
}
起初我以为我可以像这样返回一个对象文字,但事实证明这是一个语法错误.实际有什么区别?
另一个问题的示例: 如何将switch语句作为ES6中的函数参数?
以这种方式使用的大括号可以建立自己的块范围,您可以在其中定义局部let
变量或const
常量:
switch (false) {
case true: {
let x = "bar";
console.log(x);
break;
}
case false: {
let x = "baz";
console.log(x);
break;
}
}
该示例将在没有嵌套块作用域的情况下抛出,因为在Ecmascript 2015中的同一作用域中不允许使用多个具有相同标识符的let
/const
声明.
请注意,switch
语句本身会创建一个块作用域,即,无论是否使用嵌套的块作用域,switch
中的let
/const
声明都不会泄漏到父作用域中.>
但是,在switch
的上下文中,大括号也仅用于装饰,以可视地突出显示各个case
分支的块.
What's the difference between:
switch (expression) {
case:
somethings;
break;
}
and
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?
Example from another question: How to pass switch statement as function argument in Javascript ES6?
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;
}
}
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.
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.
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语句中花括号有什么作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!