javascript 终止函数执行操作


  本文标签:javascript,函数

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(); 我们看到在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便会终止 。