在函数中不能使用标签工作,将出现标签未找到错误

break not working with label inside a function error coming label not found

本文关键字:标签 错误 工作 函数 不能      更新时间:2023-09-26

//break不能处理函数内的标签错误

var a = 10 ;
function myfn(){
  if(a===15){
    break stoplabel;
  }
  else{
    console.log(a);
    a++;
    stoplabel:myfn();
  }
}
myfn();

只能在stoplabel:代码块中使用break stoplabel;

例如:

var cars = ["BMW", "Volvo", "Saab", "Ford"];
var text = [];
list: {
    text.push(cars[0]);
    text.push(cars[1]);
    text.push(cars[2]);
    break list;
    text.push(cars[3]);
    text.push(cars[4]);
    text.push(cars[5]);
}
console.log(text);

你可以这样修改你的代码:

var a = 10 ;
function myfn(){
  if(a===15){
    return;
  }
  else{
    console.log(a);
    a++;
    myfn();
  }
}
myfn();