我有一个函数:
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 myfunction() {
if(a == 'stop')
return false;
}
返回错误;比只是回报要好得多;
其他回答
你可以用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()
{
if (a == 'stop') // How can I stop working of function here?
{
return;
}
}
输入任何抛出错误的随机命令,例如:
exit
or
die:-)
使用一点不同的方法,你可以使用try catch和throw语句。
function name() {
try {
...
//get out of here
if (a == 'stop')
throw "exit";
...
} catch (e) {
// TODO: handle exception
}
}
使用return将停止函数并返回未定义的值,或者返回使用return命令指定的值。
function myfunction(){
if(a=="stop"){
//return undefined;
return; /** Or return "Hello" or any other value */
}
}