js教程

js终止函数继续执行方法

我的站长站 2023-09-24 人阅读

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

function testA(){
    alert('a');
    alert('b');
    alert('c');
}

testA(); 程序执行会依次弹出'a','b','c'。

function testA(){
    alert('a');
    return;
    alert('b');
    alert('c');
}

testA(); 程序执行弹出'a'便会终止。


2、在函数中调用函数,在被调用函数终止的同时也希望调用的函数终止

function testC(){
    alert('c');
    return;
    alert('cc');
}

function testD(){
    testC();
    alert('d');
}

我们看到在testD中调用了testC,在testC中想通过return把testD也终止了,事与愿违return只终止了testC,程序执行会依次弹出'c','d'。

function testC(){
    alert('c');
    return false;
    alert('cc');
}
function testD(){
    if(!testC()) return;
    alert('d');
}

testD(); 两个函数做了修改,testC中返回false,testD中对testC的返回值做了判断,这样终止testC的同时也能将testD终止,程序执行弹出'c'便会终止。