javascript - 如何停止递归函数?
问题描述
所以我有我的不和谐机器人的代码。假设检查用户输入的输入是否正确。基于此,自行再次运行该命令。我使用递归函数做到了。只要用户输入正确的字符串,它就可以工作。但我希望它只运行三遍。
//代码
function recurssiveShit() {
var arr = [];
var i;
let hackString = "";
//create a unique 4 digits array
while (arr.length < 4) {
var r = Math.floor(Math.random() * 9) + 1;
if (arr.indexOf(r) === -1) arr.push(r);
}
console.log(arr);
//show the array to be sorted
message.channel.send("Write it in increasing order.\n" +
`\`${arr[0]},${arr[1]},${arr[2]},${arr[3]},\``);
//sort the array in increasing order
arr.sort((a, b) => a - b);
//store the sorted array as string
for (i = 0; i < 4; i++) {
hackString += arr[i];
}
//check is user's input is same as sorted array
message.channel.awaitMessages(filter, { max: 1, time: 6000 }).then(collected => {
let check = collected.first().content;
if (check === hackString) {
message.channel.send("Hack Successful");
recurssiveShit();
}
else {
return message.channel.send("Incorrect");
}
}).catch(err => {
console.log("Time ran out");
})
console.log(hackString);
}
recurssiveShit();
解决方案
您可以在函数外部创建一个变量,在需要时递增它,并在递归触发另一个函数之前检查它是否没有超过其限制。
var count = 0;
function recurssiveShit() {
var arr = [];
var i;
let hackString = '';
//create a unique 4 digits array
while (arr.length < 4) {
var r = Math.floor(Math.random() * 9) + 1;
if (arr.indexOf(r) === -1) arr.push(r);
}
console.log(arr);
//show the array to be sorted
message.channel.send(
'Write it in increasing order.\n' +
`\`${arr[0]},${arr[1]},${arr[2]},${arr[3]},\``
);
//sort the array in increasing order
arr.sort((a, b) => a - b);
//store the sorted array as string
for (i = 0; i < 4; i++) {
hackString += arr[i];
}
//check is user's input is same as sorted array
message.channel
.awaitMessages(filter, { max: 1, time: 6000 })
.then((collected) => {
let check = collected.first().content;
if (check === hackString) {
message.channel.send('Hack Successful');
if (++count !== 3) { // increment counter, than check if it equals three
recurssiveShit();
} else {
// code...
}
} else {
return message.channel.send('Incorrect');
}
})
.catch((err) => {
console.log('Time ran out');
});
console.log(hackString);
}
recurssiveShit();
推荐阅读
- npm - npm pack 不包含包中的所有文件
- python - 如何将数据(python 列表)添加到现有 Excel 文件中的新列?
- unit-testing - 在Vue单元测试中,如何触发使用实例方法$watch创建的watcher函数
- reactjs - 将上下文从 useQuery 传递给 Apollo 客户端
- javascript - 我希望我的按钮在填写完字段后调用我的模式
- r - R 命令 polr:响应必须有 3 个或更多级别
- tensorflow-federated - TFF:具有自定义数据集的自定义输入规范 - TypeError:“TensorSpec”类型的对象没有 len()
- grep - Mercurial 是否有模板来捕获“hg grep”的输出?
- python - numpy_financial irr 函数返回“ValueError:输入必须是 rank-1 数组”
- matplotlib - 如何将多个变量添加到 matplotlib 标题