1

我正在尝试从我的变量中获取 while 循环的产品:

var firstOne = 1;
var timesBy = 0;
var result1 = function()
{
  while (timesBy < 10) {
firstOne * timesBy;
timesBy = timesBy +1; 
}
    };
console.log(result1);

我的控制台只记录 [Function],这很有意义,因为我要求它给我 result1,但当然我想要的是函数内部的 while 循环的产物。我知道这很容易,但我才刚刚开始。谢谢

4

2 回答 2

3

您需要从函数返回一个值,并调用函数本身:

var firstOne = 1;
var timesBy = 0;
var result1 = function () {
    while (timesBy < 10) {
        firstOne * timesBy; // does nothing, but I left it regardless.
        timesBy = timesBy + 1;
    }
    return timesBy; // returns the variable back to the calling-context
};
console.log(result1, result1());
//                    ^-- calls the function

JS 小提琴演示

随着更新,在评论中,关于此功能的预期结果:

var firstOne = 1;
var result1 = function () {
    for (var i = 1; i < 11; i++){
        firstOne = firstOne * i;
    }
    return firstOne;
};
console.log(result1());

JS 小提琴演示

于 2013-10-27T23:34:35.627 回答
1

你很接近:

var firstOne = 1;
var timesBy = 0;
var result1 = function () {
    while (timesBy < 10) {
        timesBy++;
        firstOne = firstOne * timesBy;
    }
    return firstOne;
};
alert(result1());

小提琴

于 2013-10-27T23:52:44.430 回答