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 API 如何获取响应体? 2022-01-01
- 失败的 Canvas 360 jquery 插件 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- 400或500级别的HTTP响应 2022-01-01
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- Flexslider 箭头未正确显示 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
