在返回值时重复函数 X 次
Repeating a function X amount of times while returning a value
我有一个代码接受用户输入的整数 "X" 然后重复它 Math.ceil(X/3)
次,所以我使用了这个。在本例中让 "X" 为 10
function repeat(func, times) {
func();
--times && repeat(func, times);
}
function test() {
console.log('test');
}
repeat(function() { test(); }, Math.ceil(10 / 3));
我想稍微调整一下,这样代码会 return 减去多少 "X" 的值直到达到 0,但如果最终值为负,它会return "X" 数量自己离开了。抱歉,如果这听起来令人困惑,我的意思是进一步阐明我的目标:
/* The user inputs X as 10
I would like the ouput to look like this: */
"test 3" //10-3=7 so 7 left, return 3 to output
"test 3" //7-3=4 so 4 left, return 3 to output
"test 3" //4-3=1 so 0 left, return 3 to output
"test 1" //1-3=-2 would be less than 0, so do 1-1 instead and that results to 0, return 1 to output and end loop
您需要 将实际数字传递给 repeat
而不仅仅是 10/3
的结果,否则它不知道何时停止。
演示
function repeat(func, num1, num2 )
{
num1 > num2 ? func(num2) : func(num1);
if ( num1 > num2 )
{
num1 -= num2;
repeat(func, num1, num2);
}
}
function test(times) {
console.log('test', times)
}
repeat(test, 10, 3);
我有一个代码接受用户输入的整数 "X" 然后重复它 Math.ceil(X/3)
次,所以我使用了这个。在本例中让 "X" 为 10
function repeat(func, times) {
func();
--times && repeat(func, times);
}
function test() {
console.log('test');
}
repeat(function() { test(); }, Math.ceil(10 / 3));
我想稍微调整一下,这样代码会 return 减去多少 "X" 的值直到达到 0,但如果最终值为负,它会return "X" 数量自己离开了。抱歉,如果这听起来令人困惑,我的意思是进一步阐明我的目标:
/* The user inputs X as 10
I would like the ouput to look like this: */
"test 3" //10-3=7 so 7 left, return 3 to output
"test 3" //7-3=4 so 4 left, return 3 to output
"test 3" //4-3=1 so 0 left, return 3 to output
"test 1" //1-3=-2 would be less than 0, so do 1-1 instead and that results to 0, return 1 to output and end loop
您需要 将实际数字传递给 repeat
而不仅仅是 10/3
的结果,否则它不知道何时停止。
演示
function repeat(func, num1, num2 )
{
num1 > num2 ? func(num2) : func(num1);
if ( num1 > num2 )
{
num1 -= num2;
repeat(func, num1, num2);
}
}
function test(times) {
console.log('test', times)
}
repeat(test, 10, 3);