【问题标题】:Creating a variable with a function to RETURN, which could then be put inside a second variable创建一个带有返回函数的变量,然后可以将其放入第二个变量中
【发布时间】:2013-08-17 19:22:33
【问题描述】:

我正在 Codecademy 上学习 JavaScript,并尝试创建将返回值的变量,然后在另一个变量中使用该变量。有谁知道为什么下面的代码没有做到这一点?我收到“语法错误”消息。

// Parameter is a number, and we do math with that parameter
var timesTwo = function(number) {
        return number * 2;
    };
// Call timesTwo here!
var newNumber = timesTwo(number) {
    console.log(newNumber);
}
newNumber(6)

/Users/Michael/Desktop/Scr​​een Shot 2013-08-17 at 2.13.30 PM.png

【问题讨论】:

  • 就用var newNumber = function (num) { console.log(timesTwo(num)); };:jsfiddle.net/aGjeK

标签: javascript function return var


【解决方案1】:

这是定义函数的方式:

var func = function () {
    //do whatever
};

这就是你的称呼:

func();

您的代码(复制如下)会引发错误,因为它不遵守规则。应该是这样的:

//define one function
var timesTwo = function (number) {
    return number * 2;
};

//define another function
var newNumber = function (number) {
    //timesTwo is called inside
    console.log( timesTwo(number) );
};

//call newNumber which calls timesTwo itself
newNumber(6);

【讨论】:

    【解决方案2】:

    正如 JOPLOmacedo 所说,您正在混合函数声明和调用语法。当你说“变量”时,我不确定你是指“函数”(只有函数可以返回),还是其他类型的变量。

    也许这就是你想要完成的:

    var newNumber = timesTwo(6);
    console.log(newNumber); // logs 12
    

    【讨论】:

      【解决方案3】:

      您可以尝试以下方法吗? http://jsfiddle.net/LE5rY/

      // Parameter is a number, and we do math with that parameter
      var timesTwo = function(number) {
      return number * 2;
      };
      // Call timesTwo here!
      var newNumber = function(number) {
      console.log(timesTwo(number));//edit here
      };
      newNumber(6);
      

      【讨论】:

        猜你喜欢
        • 2013-05-31
        • 2020-12-01
        • 2012-11-21
        • 1970-01-01
        • 2021-12-27
        • 2018-02-01
        • 1970-01-01
        • 1970-01-01
        • 2015-10-19
        相关资源
        最近更新 更多