我正在尝试从变量中获取 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
随着更新,在评论中,关于这个功能的预期结果:
var firstOne = 1;
var result1 = function () {
for (var i = 1; i < 11; i++){
firstOne = firstOne * i;
}
return firstOne;
};
console.log(result1());
关于javascript - 如何在变量中返回 while 循环的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19624971/