javascript - 如何在变量中返回 while 循环的结果

标签 javascript function while-loop

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

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

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

最佳答案

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

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 Fiddle demo .

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

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

JS Fiddle demo .

关于javascript - 如何在变量中返回 while 循环的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19624971/

相关文章:

javascript - 无法在哈巴狗上显示图像

javascript - 避免重复代码

javascript - 函数异议符号?

php - 我如何使用数组中的值? (php)

javascript - Cheeriojs 出现错误 : exports. load.initialize

javascript - ReactJs setState 回调不工作

javascript - 表单帮助 : input - output for math function

c - NaN 在与使用 x87 浮点的汇编混合的 C 代码中意外出现

c++ - 在 C++ 中创建循环(仍在学习中)

c - 为什么 Scanf 在获取角色时工作很奇怪