JS中带标签(Labeled statements)的switch、while如何使用

178 阅读1分钟

最近偶然发现一种非常少用的见的js语法

案例一 switch语句语法

switch里套switch

const count = '2' as string;
const type = '3' as string;
label: switch (count) {
  case '1': {
    console.log('count', 1); 
    break;
  }
  case '2': {
    console.log('count', 2);
    switch (type) {
      case '3': {
        console.log('type', 3);

        break label;
      }
      case '4': {
        console.log('type', 4);
        break
      }
      default: {
        console.log('default type');
      }
    }
    break;
  }
  default : {
    console.log('default count');
  }
}

上面的代码将打印

count 2
type 3

语法label: switch (count) {...},相当于我们给switch (count) {...}打了个名为label的标签,当我们在内层中需要进一步细化再次使用switch语法时,可以调用break label来跳出外层的switch语句(请注意,内层的switch语句也会跳出)

那我做些修改

const count = '2' as string;
const type = '3' as string;
label: switch (count) {
  case '1': {
    console.log('count', 1); 
    break;
  }
  case '2': {
    console.log('count', 2);
    switch (type) {
      case '3': {
        console.log('type', 3);
-        break label;
+        break
      }
      case '4': {
        console.log('type', 4);
-        break
      }
      default: {
        console.log('default type');
      }
    }
-    break;
  }
  default : {
    console.log('default count');
  }
}

此时打印

count 2
type 3
default count

可见在内层的switch单纯调用break并不能使外层switch跳出,需要加上break label来跳出

案例二 while循环语法,跟switch语法类似,大家可以本地尝试下

let statements1 = 'xxx';
let statements2 = 'yyy';

outer:
    while (statements1) {
        ...
        while (statements2) {
            ....
            break outer;
        }
    }