What do the curly braces do in switch statement after case in es6?(es6 中的 case 之后的 switch 语句中的花括号有什么作用?)
问题描述
两者有什么区别:
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 语句中的花括号有什么作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:es6 中的 case 之后的 switch 语句中的花括号有什么作用?
基础教程推荐
- fetch 是否支持原生多文件上传? 2022-01-01
- Bokeh Div文本对齐 2022-01-01
- Bootstrap 模态出现在背景下 2022-01-01
- npm start 错误与 create-react-app 2022-01-01
- 在 contenteditable 中精确拖放 2022-01-01
- 检查 HTML5 拖放文件类型 2022-01-01
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01
- 如何添加到目前为止的天数? 2022-01-01
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01
- Fabric JS绘制具有活动形状的多边形 2022-01-01
