【问题标题】:Illegal return statement error非法返回语句错误
【发布时间】:2013-11-26 17:50:08
【问题描述】:

我的退货声明有什么问题?

var creditCheck = function (income) {
    var val = income;
    return val;
};
if (creditCheck > 100) {
    return "You earn a lot of money! You qualify for a credit card.";
} else {
    return "Alas, you do not qualify for a credit card. Capitalism is cruel like that.";
}
console.log(creditCheck(75));

【问题讨论】:

  • 确切的异常消息是什么?
  • 你的代码看起来很糟糕。您创建一个函数,然后测试该函数是否大于 100?
  • 这里是代码学院。
  • 这看起来很可疑:if (creditCheck > 100)。将函数与数字进行比较是没有意义的。

标签: javascript if-statement return


【解决方案1】:

您的return 语句在任何函数之外。您只能在函数中使用return

(您还在将函数与整数进行比较,if (creditCheck > 100) - 您的意思是在此处调用该函数吗?)

【讨论】:

    【解决方案2】:

    重新缩进和简化代码揭示:

    var creditCheck = function(income) {
        return income; // essentially a no-op
    };
    if( creditCheck > 100) { // if a function is greater than a number?
        return "You earn a lot...";
        // is this code in a function? Otherwise it's an invalid return!
    }
    // else is unnecessary, due to `return` above.
    return "Alas, you lack basic JavaScript knowledge...";
    // console.log is never reached due to `return`.
    

    查看 cmets - 有很多错误!

    【讨论】:

      【解决方案3】:
      if (creditCheck > 100) {
          return "You earn a lot of money! You qualify for a credit card.";
      } else {
          return "Alas, you do not qualify for a credit card. Capitalism is cruel like that.";
      }
      

      这两个返回都是无效的,因为它们不在函数内。

      (creditCheck > 100) 无效,因为 credicheck 是一个函数,需要提供一个变量才能返回任何内容

      var creditCheck = function (income) {
          return income;
      };
      if (creditCheck(50) > 100) {
          console.log("You earn a lot of money! You qualify for a credit card.");
      } else {
          console.log("Alas, you do not qualify for a credit card. Capitalism is cruel like that.");
      }
      

      会补充一句,你没有资格获得信用卡。资本主义就是这么残酷。到控制台日志

      下载http://www.helpmesh.net/s/JavaScript/javascript.chm 以获取javascript 的基本语法,您将节省大量时间。您遇到的问题类型和语法并不是创建 stackexchange 的目的。

      【讨论】:

        【解决方案4】:

        我在下面对您的问题进行了一些澄清。希望对您有所帮助。

        var income = 50; // 首先,你需要申报收入,在这种情况下我设置为 50//

        //然后您需要将 creditCheck 声明为收入的函数。请注意,return 仅适用于函数。要在函数之外打印到控制台,请使用 console.log()//

        var creditCheck = function (income) {
          if (income > 100) {
            return "You earn a lot of money! You qualify for a credit card.";} 
            else {
                return "Alas, you do not qualify for a credit card. Capitalism is cruel like that.";
            }
        };
        
        creditCheck(income); //You can execute the function by calling it.//
        

        //下面的文本显示了在执行函数时打印到控制台的内容//

        “唉,你没有资格获得信用卡。资本主义就像残酷一样 那个。”

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2013-06-18
          • 2021-09-28
          • 1970-01-01
          • 2015-04-13
          • 2013-10-06
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多