如何退出 javascript 函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10459207/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 01:24:09  来源:igfitidea点击:

How can I exit from a javascript function?

javascriptjquery

提问by Samantha J T Star

I have the following:

我有以下几点:

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

I would like to exit from this function if an "if" condition is met. How can I exit? Can I just say break, exit or return?

如果满足“if”条件,我想退出此函数。我怎样才能退出?我可以说休息、退出或返回吗?

回答by Florian Margaine

if ( condition ) {
    return;
}

The returnexits the function returning undefined.

return退出函数返回undefined

The exitstatement doesn't exist in javascript.

exit语句在 javascript 中不存在。

The breakstatement allows you to exit a loop, not a function. For example:

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

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

This also works with the forand the switchloops.

这也适用forswitch循环和循环。

回答by Adil

Use return statement anywhere you want to exit from function.

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

if(somecondtion)
   return;

if(somecondtion)
   return false;

回答by thecodeparadox

you can use

您可以使用

return false;or return;within your condition.

return false;return;在您的条件下。

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

回答by Sam T

Use this when if satisfies

当满足时使用这个

do

return true;

回答by Yosep Kim

You should use return as in:

您应该使用 return :

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

回答by Rodrigo E. Principe

I had the same problem in Google App Scripts, and solved it like the rest said, but with a little more..

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

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

This way you not only exit the function, but show a message saying why it stopped. Hope it helps.

通过这种方式,您不仅可以退出函数,还可以显示一条消息,说明它为什么停止。希望能帮助到你。