为什么 const 在开关大小写语句中是非法的

Why is const illegal in a switch case statement?

本文关键字:非法 语句 大小写 const 开关 为什么      更新时间:2023-09-26

为什么在交换机内的机箱块中不允许使用常量?

这将生成一个 JS 错误:

(function () {
    "use strict";
    const foo = "bar";
    switch (foo) {
        case "bar":
            const bar = "foo"; // error
            console.log("bar is", bar);
            break;
        default:
            console.log("nope");
            break;
    }
}());

但这有效:

(function () {
    "use strict";
    const foo = "bar";
    switch (foo) {
        case "bar":
            var bar = "foo"; // error
            console.log("bar is", bar);
            break;
        default:
            console.log("nope");
            break;
    }
}());

我一直在浏览 ECMASCript 规范,它并没有跳出来为什么不允许这样做。 const允许在LexicalEnvironment中。案例块是一种特殊的 JavaScript 块吗?还是这是一个错误?

编辑

这是Chrome 42中的一个错误。更新到Chrome 43修复了它。

量的值不能通过重新赋值来更改,并且常量不能重新声明。

您可以从 MDN 查看有关 const 的更多详细信息:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const