我正在尝试从变量中获取while循环的乘积:
var firstOne = 1;
var timesBy = 0;
var result1 = function()
{
while (timesBy < 10) {
firstOne * timesBy;
timesBy = timesBy +1;
}
};
console.log(result1);
我的控制台只记录[功能]这是有道理的,因为我要求它给我result1,但当然我想要的是函数里面的while循环的产品。我知道这很简单,但我刚开始。 感谢
答案 0 :(得分: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
在评论中,有关此功能的预期结果的更新:
var firstOne = 1;
var result1 = function () {
for (var i = 1; i < 11; i++){
firstOne = firstOne * i;
}
return firstOne;
};
console.log(result1());
答案 1 :(得分:1)
你很亲密:
var firstOne = 1;
var timesBy = 0;
var result1 = function () {
while (timesBy < 10) {
timesBy++;
firstOne = firstOne * timesBy;
}
return firstOne;
};
alert(result1());