如何提前退出javascript脚本代码?

时间:2015-06-04 10:30:20

标签: javascript web-frontend

我有一个页面,有很多......部分。在其中一个中,我得到它的一半并决定我想停止,而不是运行此脚本标记的其余内容 - 但仍然在页面上运行其他代码段。有没有办法在函数调用中不用包装整个代码段?

例如:

<script type='text/javascript'>
    console.log('1 start');
    /* Exit here */
    console.log('1 end');
</script>
<script type='text/javascript'>
    console.log('2 start');
    console.log('2 end');
</script>

应该产生输出

1 start
2 start
2 end

而不是1 end

显而易见的答案是将脚本包装在一个函数中:

<script type='text/javascript'>
    (function(){
        console.log('1 start');
        return;
        console.log('1 end');
    })();
</script>

虽然这通常是最好的方法,但有些情况并不合适。所以我的问题是,如果有的话,还有什么其他方式呢?或者如果没有,为什么不呢?

3 个答案:

答案 0 :(得分:2)

您可以使用break语句:

&#13;
&#13;
breakCode : {
  document.write('1 start');
  /* Exit here */
  break breakCode;
  document.write('1 end');
}
&#13;
&#13;
&#13;

使用标签引用,break语句可用于跳出任何代码块

参考

答案 1 :(得分:0)

实现所需内容的一种方法(停止执行给定的脚本块,而不将其包装在函数中)是抛出错误。

<script type='text/javascript'>
    console.log('1 start');
    throw new Error();
    console.log('1 end');
</script>

当然,这样做的缺点是会导致错误记录到控制台。

答案 2 :(得分:0)

如果您想使用 throw 方法(在 @knolleary's answer 中提到)停止脚本标记,但又不想在控制台中抛出错误消息,请使用以下方法:

<script>
  console.log("This will get logged to console.");
  window.onerror = () => { window.onerror=undefined; return true; }
  throw 0;
  console.log("This won't.");
</script>

该代码仅使用 window.onerror 捕获错误(返回 true 会隐藏错误)。

如果您需要经常使用它,当然可以创建一个全局函数:

<script>
  function scriptReturn() {
    window.onerror = () => { window.onerror=undefined; return true; }
    throw 0;
  }
</script>
...
<script>
  console.log("This will get logged to console.");
  scriptReturn();
  console.log("This won't.");
</script>

如果您需要在代码的其他地方使用 window.onerror,您可以使用 addEventListener

window.addEventListener("error", function(e) { ... })