es6中的case后在switch语句中花括号有什么作用? [英] What do the curly braces do in switch statement after case in es6?

查看:694
本文介绍了es6中的case后在switch语句中花括号有什么作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

之间有什么区别

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆