如何退出 javascript 函数



>我有以下内容:

function refreshGrid(entity) {
    var store = window.localStorage;
    var partitionKey;
    ...
    ...
如果

满足"如果"条件,我想退出此功能。如何退出?我可以说中断,退出或返回吗?

if ( condition ) {
    return;
}

return退出返回undefined的函数。

exit语句在 javascript 中不存在。

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

var i = 0;
while ( i < 10 ) {
    i++;
    if ( i === 5 ) {
        break;
    }
}

这也适用于forswitch循环。

在要退出函数的任何位置使用 return 语句。

if(somecondtion)
   return;
if(somecondtion)
   return false;
您可以使用

return false;return;符合您的病情。

function refreshGrid(entity) {
    var store = window.localStorage;
    var partitionKey;
    ....
    if(some_condition) {
      return false;
    }
}

如果满足

return true;

您应该使用 return 如下:

function refreshGrid(entity) {
  var store = window.localStorage;
  var partitionKey;
  if (exit) {
    return;
  }

我在Google App Scripts中遇到了同样的问题,并像其他人所说的那样解决了它,但还有更多。

function refreshGrid(entity) {
var store = window.localStorage;
var partitionKey;
if (condition) {
  return Browser.msgBox("something");
  }
}

这样,您不仅可以退出函数,还可以显示一条消息,说明它停止的原因。希望对您有所帮助。

最新更新