【问题标题】:Breaking out of one JS function to call another JS function跳出一个 JS 函数调用另一个 JS 函数
【发布时间】:2014-02-27 03:44:18
【问题描述】:

假设我有一系列函数:

function a(){
   //do this, do that
   b();
}
function b(){
   //do this, do that
   c();
}
function c(){
   //do this, do that
   // program ends at this point
}
a();

你会假设通过执行代码,我们从a()b()c() 并且程序终止......

我想知道的是...是否可以将代码放置在 b()// do this, do that 部分中的某处,根据特定条件返回到 a() 然后继续进行而不需要返回 where它在b() 中停止,但如果需要可以重新启动b()

我知道,你在想什么......“这是一个 JavaScript GOTO 问题,当然!”在某种程度上它是......但说真的,是否有可能完全脱离函数 A 并转到函数 B 而不必担心它返回到函数 A 以完成它停止的地方?

【问题讨论】:

  • depending on certain conditions to return to a() 你回答了你自己的问题:return "value"; :)

标签: javascript function goto


【解决方案1】:

你可以像这样使用 JavaScript 的 return 语句

function a(){
   //do this, do that
   b();
}
function b(){
   if (some_random_condition) {
      return;
   }
   c();
}
a();

return 语句可以转到a,而无需执行b 函数的其余部分。

【讨论】:

  • 我尝试了以下方法:var a, b; function fa(){a = 1;b = 10;fb();} function fb(){document.write("a = "+ a + "<br>");fc();} function fc(){if(a<b){a++;fb();return;}else{document.write("That's the end.<br>");}} fa(); 令人惊讶的是它的工作方式符合我的预期......谢谢!
猜你喜欢
  • 2020-11-17
  • 1970-01-01
  • 1970-01-01
  • 2023-02-01
  • 2017-11-28
  • 1970-01-01
  • 1970-01-01
  • 2020-06-11
  • 1970-01-01
相关资源
最近更新 更多