在 C 中,您可以将变量范围限定为 switch case,例如 this .
使用 javascript,我使用以下命令获得了意外的 token :
const i = 1
switch (i) {
// variables scoped to switch
var s
var x = 2342
case 0:
s = 1 + x
break
case 1:
s = 'b'
break
}
有没有其他方法可以做到这一点,或者我应该在开关之外声明我的变量?
编辑:
这是我考虑过的一种解决方法,但最终没有奏效。原因是每个案例都有自己的范围。
const i = 1
switch (i) {
case i:
// variables scoped to switch
var s
var x = 2342
case 0:
s = 1 + x
break
case 1:
s = 'b'
break
}
最佳答案
一些替代方案:
/* curly braces inside the case */
const i = 1
switch (i) {
case 0: {
let x = 2342;
let s = 1 + x;
console.log(x+' & '+s+' from inside');
} break;
case 1: {
let x = 2342;
let s = 'b';
console.log(x+' & '+s+' from inside'); /* 2342 & b from inside */
} break;
}
console.log(x+' & '+s+' from outside'); /* Uncaught ReferenceError */
或者
/* curly braces outside the switch */
const i = 1
{
let x = 2342;
let s;
switch (i) {
case 0:
s = 1 + x;
break;
case 1:
s = 'b';
break;
}
console.log(x+' & '+s+' from inside'); /* 2342 & b from inside */
}
console.log(x+' & '+s+' from outside'); /* Uncaught ReferenceError */
关于Javascript范围变量切换大小写?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40999025/