Javascript - 尝试将函数分配给变量

时间:2017-03-21 22:49:46

标签: javascript

我只是在javascript中编写一个非常简单的函数来计算阶乘。据我所知,在javascript中你可以为变量赋一个函数。

所以我在在线编译器(https://repl.it/languages/javascript)上试过这个,这就是我的代码看起来像

var mynum = prompt("Enter a number", "<enter a number>");
var answer;
if (isNaN(mynum)){
 console.log(mynum +" is not a number");
}
else{
 console.log("You entered "+mynum);
 answer = function (mynum){
            var i = mynum-1;
            var temp = mynum;
            while(i>0){
              temp = temp*i;
              i--;
            }
            return temp;
  };
 console.log("the factorial of "+mynum+" is "+answer);
}

但是当我运行它时,输出会将整个函数包含在“回答”

You entered 23
the factorial of 23 is function (mynum) {var _loopStart = Date.now(),_loopIt =     0;
var i = mynum - 1;
var temp = mynum;setTimeout(function () {_loopStart = Infinity;});
while (i > 0) {if (++_loopIt > 5000 && Date.now() - _loopStart > 150) throw new RangeError("Potential infinite loop. You can disable this from settings.");
  temp = temp * i;
  i--;
}
return temp;

}

但是,当我创建函数然后单独调用它时,我没有这个问题(类似于answer = function(mynum)。

任何人都可以告诉我为什么会这样吗?

谢谢!

4 个答案:

答案 0 :(得分:1)

为变量分配函数与分配其评估不同。

在您的情况下,您有两种解决方案:

在记录时对您指定的功能进行有效调用:

console.log("the factorial of "+mynum+" is "+answer(mynum));

在指定时间对指定的功能进行有效调用:

answer = (function (mynum){
  var i = mynum-1;
  var temp = mynum;
  while(i > 0) {
    temp = temp*i;
    i--;
  }
  return temp;
}(mynum));

两种解决方案都非常适合您的具体情况。

<强>为什么吗

因为声明了这样的函数:

var func = function () {
  console.log("Hello!");
};

或者像这样:

function func () {
  console.log("Hello!");
};

little difference

答案 1 :(得分:1)

正如所指出的,你必须把它称为一个函数。

var mynum = prompt("Enter a number", "<enter a number>");
var answer;
if (isNaN(mynum)){
 console.log(mynum +" is not a number");
}
else{
 console.log("You entered "+mynum);
 answer = function (mynum){
            var i = mynum-1;
            var temp = mynum;
            while(i>0){
              temp = temp*i;
              i--;
            }
            return temp;
  };
 console.log("the factorial of "+mynum+" is "+answer (mynum));
}

或者,您可以使用IIEF(立即调用的函数表达式):

var mynum = prompt("Enter a number", "<enter a number>");
var answer;
if (isNaN(mynum)){
 console.log(mynum +" is not a number");
}
else{
 console.log("You entered "+mynum);
 answer = (function (mynum){
            var i = mynum-1;
            var temp = mynum;
            while(i>0){
              temp = temp*i;
              i--;
            }
            return temp;
  })(mynum);
 console.log("the factorial of "+mynum+" is "+answer);
}

请注意,我在函数周围添加了一个括号并传入了参数。这就是你可以立即调用函数的方法。

答案 2 :(得分:0)

answer()等javascript中返回函数时。你必须这样称呼它。

  

console.log(“the factorial of”+ mynum +“是”+ answer(mynum));

答案 3 :(得分:0)

您需要通过调用它来编写函数,即

{{1}}