簡體   English   中英

如何停止遞歸函數?

[英]How to stop a recursive function?

所以我有這個代碼用於我的不和諧機器人。 假設檢查用戶輸入的輸入是否正確。 基於它自己再次運行命令。 我是用遞歸函數做的。 只要用戶輸入正確的字符串,它就可以工作。 但我希望它只運行三遍。

//代碼

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM