Javascript作用域变量可以切换大小写吗?

2024-04-26

在 C 中,您可以将变量的范围限定为 switch case,例如this https://stackoverflow.com/a/2101514/773263.

使用 javascript,我使用以下命令获得意外的令牌:

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
}

还有另一种方法可以做到这一点还是我应该在开关之外声明我的变量?

EDIT:

这是我考虑过的解决方法,但最终没有成功。原因是每个案例都有其自己的范围。

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 */

or

/* 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 */
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Javascript作用域变量可以切换大小写吗? 的相关文章

随机推荐