Javascript 从函数内部返回函数

Javascript returning out of a function inside a function

鉴于此代码:

var x=5;
var fx=function(){
    console.log("hey");
    (function(){
        if (x==5){
            console.log('hi');
            return;
        }
    })();
    console.log('end');
};

fx();

如何 return 使最终 console.logx==5 时不执行?

我是 javascript 的新手,所以我可能漏掉了什么...

你不能像那样 return,相反你可以使用标志或使内部函数 return 像

这样的值

var x = 5;
var fx = function() {
  snippet.log("hey");

  var flag = (function() {
    if (x == 5) {
      snippet.log('hi');
      return false;
    }
  })();
  //if the returned value is false then return
  if (flag === false) {
    return
  }
  snippet.log('end');
};

fx();
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

var x = 5;
var fx = function() {
  console.log("hey");

  if (x == 5) {
    console.log('hi');
    return;
  }

  console.log('end');
};

fx();

您可以使用 if 语句或 else,具体取决于您要执行的操作

如果

var x=5; var fx=function(){
    console.log("hey");
    (function(){
        if (x==5){
            console.log('hi');
            return;
        }
    })();
    if(x != 5){
        console.log('end');
    } };

fx();

其他

var x=5;
var fx=function(){
    console.log("hey");
    (function(){
        if (x==5){
            console.log('hi');
            return;
        } else {
            console.log('end');
        }
    })();
};

fx();

您可以将函数包装到条件

var x=5;
var fx=function(){
   console.log("hey");
   if( !(function(){
       if (x==5){
           console.log('hi');
           return true;
       }
    })() ){
       console.log('end');
    }
};

fx();

JSFIDDLE DEMO