gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 10:25:48 25 4
gpt4 key购买 nike

我正在尝试从变量中获取 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com