【问题标题】:javascript return statement to stop executing the rest of statementsjavascript return 语句停止执行其余语句
【发布时间】:2020-03-15 17:52:25
【问题描述】:

如果前一个函数有 return 语句,我想中断下一个函数调用,但我可以看到它正在执行下一个函数调用,即使我在下面名为“b”的函数中有 return 语句。

function main(){
  a()
  b();
  c();
}

function a(){
  console.log("function a call!!");
}
function b(){
  console.log("function b call!!");
  return function(){return 0;}
}
function c(){
  console.log("function c call!!");
}

main()

输出:

'function a call!!'
'function b call!!'
'function c call!!'

预期输出:

'function a call!!'
'function b call!!'

有人可以解释一下这里的正确做法吗?

【问题讨论】:

  • 你的 main 函数应该有 return 语句来破坏该函数。这里 retun on function b 将从 b 返回到 main function 而不是 main function。
  • 理想情况下,如果“b”函数基于某些条件调用,我想阻止“c”函数调用。如果我的 b 函数如下: function b() { return; }...还是不行...

标签: javascript scope return


【解决方案1】:

您不能从被调用函数对调用函数执行控制流。您的代码只是从b() 返回一个function,但该函数永远不会执行,即使是,它也不会具有预期的行为。如果你想打断main,必须在main本身中进行:

function main(){
  a()
  const bReturnValue = b();
  if(bReturnValue <some condition>) {
      return;
  }
  c();
}

function a(){
  console.log("function a call!!");
}
function b(){
  console.log("function b call!!");
  return function(){return 0;}
}
function c(){
  console.log("function c call!!");
}

main()

【讨论】:

  • 感谢 Guerric 的解释。
【解决方案2】:

你不能取消 C 的函数调用,因为你不检查 b 返回的内容。例如,让 b 返回 true,并使用

进行检查
let resultB = b();
if(!resultB) c();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-10
    • 2012-04-18
    • 2019-08-12
    • 2012-03-18
    • 2020-12-12
    • 1970-01-01
    • 2023-02-23
    相关资源
    最近更新 更多