我有一个函数:
function myfunction() {
if (a == 'stop') // How can I stop the function here?
}
JavaScript中是否有类似exit()的东西?
我有一个函数:
function myfunction() {
if (a == 'stop') // How can I stop the function here?
}
JavaScript中是否有类似exit()的东西?
当前回答
如果你正在使用jquery。这将阻止函数冒泡到,因此父函数调用它也应该停止。
function myfunction(e)
{
e.stopImmediatePropagation();
................
}
其他回答
你可以用return。
function myfunction() {
if(a == 'stop')
return;
}
这将向调用函数的对象发送一个undefined的返回值。
var x = myfunction();
console.log( x ); // console shows undefined
当然,您可以指定不同的返回值。无论返回的值是什么,都将使用上面的示例记录到控制台。
return false;
return true;
return "some string";
return 12345;
显然你可以这样做:
function myFunction() {myFunction:{
console.log('i get executed');
break myFunction;
console.log('i do not get executed');
}}
通过使用标签查看块作用域:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/label
我还看不出有什么不好。但这似乎不是一种常用的用法。
推导出这个答案:JavaScript等价于PHP的die
退出();可以用来进行下一次验证。
我不喜欢回答那些不是真正解决方案的问题……
...但当我遇到同样的问题时,我采取了以下解决方案:
function doThis() {
var err=0
if (cond1) { alert('ret1'); err=1; }
if (cond2) { alert('ret2'); err=1; }
if (cond3) { alert('ret3'); err=1; }
if (err < 1) {
// do the rest (or have it skipped)
}
}
希望对大家有用。
这样的:
function myfunction()
{
if (a == 'stop') // How can I stop working of function here?
{
return;
}
}