我有一个代码,它接收一个整数"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));
我想对此做一些调整,以便代码返回减去多少"X“的值,直到它达到0,但是如果最后值为负值,它将返回"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发布于 2018-02-12 10:28:57
您需要将实际数字传递给repeat,而不仅仅是10/3的结果,因为它不知道什么时候停止。
Demo
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);
https://stackoverflow.com/questions/48744018
复制相似问题