我有一个函数:
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();
................
}
其他回答
如果你正在使用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;
使用一点不同的方法,你可以使用try catch和throw语句。
function name() {
try {
...
//get out of here
if (a == 'stop')
throw "exit";
...
} catch (e) {
// TODO: handle exception
}
}
这样的:
function myfunction()
{
if (a == 'stop') // How can I stop working of function here?
{
return;
}
}
显然你可以这样做:
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