这是我的代码...
handleGenNums()
{
const genNum = Math.ceil(Math.random() * 70);
if (this.state.nums.indexOf(genNum) === -1)
{
this.setState(() => {
return {
nums: this.state.nums.concat(genNum)
}
});
}
else
{
this.handleGenNums();
}
}
// handlePlayLottery() {
// while (this.state.nums.length <= 5) {
// this.handleGenNums();
// }
// }
我有一个将一个数字插入数组的按钮。我想按一下按钮,但我的数组中有5个数字。我注释掉了我尝试的代码,因为它破坏了我的浏览器。任何帮助将不胜感激。
答案 0 :(得分:0)
如果您想重复使用此功能,则可以简单地使用一个助手函数,该函数会多次调用该函数:
function callFunction(fn, n) {
if (n <= 0) return;
fn();
callFunction(fn, --n);
}
function callFunction(fn, n) {
if (n <= 0) return;
fn();
callFunction(fn, --n);
}
callFunction(() => console.log("test"), 5);
答案 1 :(得分:0)
我将向您展示如何使用递归功能。解释在代码内。
handleGenNums(counter)
{
// Check if we have to generate another number.
if (counter <= 0)
return;
// Generate a random number.
const genNum = Math.ceil(Math.random() * 70);
// Check if the generated number already is in the array.
// If number is not found, add the number, and call recursively
// the method with counter decremented. If element exists, call
// recursively again without decrementing the counter.
if (this.state.nums.indexOf(genNum) === -1)
{
this.setState(() => {
return {
nums: this.state.nums.concat(genNum)
}
});
this.handleGenNums(counter - 1);
}
else
{
this.handleGenNums(counter);
}
}
现在,如果要生成5个随机数,只需致电:
handleGenNums(5);
答案 2 :(得分:-1)
如果您要基于某种条件调用事件处理程序一定次数,则只需使用:
if(array.length < 5) {
this.handleFunction();
}