如何退出javascript函数?

Sam*_*tar 51 javascript jquery

我有以下内容:

function refreshGrid(entity) {
    var store = window.localStorage;
    var partitionKey;
    ...
    ...
Run Code Online (Sandbox Code Playgroud)

如果满足"if"条件,我想退出此函数.我该怎么退出?我可以说休息,退出还是退货?

Flo*_*ine 94

if ( condition ) {
    return;
}
Run Code Online (Sandbox Code Playgroud)

return退出函数返回undefined.

exit语句在javascript中不存在.

break语句允许您退出循环,而不是函数.例如:

var i = 0;
while ( i < 10 ) {
    i++;
    if ( i === 5 ) {
        break;
    }
}
Run Code Online (Sandbox Code Playgroud)

这也适用于forswitch循环.


Adi*_*dil 13

在任何想要退出函数的地方使用return语句.

if(somecondtion)
   return;

if(somecondtion)
   return false;
Run Code Online (Sandbox Code Playgroud)


the*_*dox 7

您可以使用

return false;return;在你的条件下.

function refreshGrid(entity) {
    var store = window.localStorage;
    var partitionKey;
    ....
    if(some_condition) {
      return false;
    }
}
Run Code Online (Sandbox Code Playgroud)


Sam*_*m T 5

如果满足,请使用此选项

return true;
Run Code Online (Sandbox Code Playgroud)