我有一个函数:
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()的东西?
当前回答
我不喜欢回答那些不是真正解决方案的问题……
...但当我遇到同样的问题时,我采取了以下解决方案:
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')
return false;
}
返回错误;比只是回报要好得多;
显然你可以这样做:
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
退出();可以用来进行下一次验证。
使用一点不同的方法,你可以使用try catch和throw语句。
function name() {
try {
...
//get out of here
if (a == 'stop')
throw "exit";
...
} catch (e) {
// TODO: handle exception
}
}
你可以用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;