当前位置: 无忧屋首页 > 文章中心 > 前端 >

js终止函数继续执行方法

来源:网络

发布人:天道酬勤

发布时间:2024-01-27

1、终止一个函数用return即可

  1. function testA(){
  2.     alert('a');
  3.     alert('b');
  4.     alert('c');
  5. }
  6. testA(); 程序执行会依次弹出'a','b','c'。

  7. function testA(){
  8.     alert('a');
  9.     return;
  10.     alert('b');
  11.     alert('c');
  12. }
  13. testA(); 程序执行弹出'a'便会终止。
2、在函数中调用函数,在被调用函数终止的同时也希望调用的函数终止
  1. function testC(){
  2.     alert('c');
  3.     return;
  4.     alert('cc');
  5. }

  6. function testD(){
  7.     testC();
  8.     alert('d');
  9. }
我们看到在testD中调用了testC,在testC中想通过return把testD也终止了,事与愿违return只终止了testC,程序执行会依次弹出'c','d'。
  1. function testC(){
  2.     alert('c');
  3.     return false;
  4.     alert('cc');
  5. }
  6. function testD(){
  7.     if(!testC()) return;
  8.     alert('d');
  9. }
testD(); 两个函数做了修改,testC中返回false,testD中对testC的返回值做了判断,这样终止testC的同时也能将testD终止,程序执行弹出'c'便会终止。

免责声明:文中图文均系网友发布,转载来自网络,如有侵权请联系右侧客服QQ删除,无忧屋网友发布此文仅为传递信息,不代表无忧屋平台认同其观点。