首页 > 解决方案 > 如何停止递归函数?

问题描述

所以我有我的不和谐机器人的代码。假设检查用户输入的输入是否正确。基于此,自行再次运行该命令。我使用递归函数做到了。只要用户输入正确的字符串,它就可以工作。但我希望它只运行三遍。

//代码

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();

标签: javascriptdiscorddiscord.jsbots

解决方案


您可以在函数外部创建一个变量,在需要时递增它,并在递归触发另一个函数之前检查它是否没有超过其限制。

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();

推荐阅读