簡體   English   中英

為什么 Javascript 中的新陣列沒有被我得到的結果推動?

[英]Why new array in Javascript not getting pushed by the results I got?

我在我的網站上研究 Magic 8 ball,不得不在 JS 上編寫代碼。 一切都很好,直到我決定不讓隨機答案重復 5 次。 所以基本上,我想要一個包含我得到的 5 個最后結果的數組。

const responses = ["keep up", "no", "dont even think", 
"very doubtful", "outlook good", "my sources say no", 
"it is decidedly so", "dont count on it", "it is certain", 
"ask again later", "reply hazy, try again", "outlook not so good", 
"cannot predict now", "better not tell you now", "definetely - yes", "most likely"];

function randomly() {
    const random = Math.floor(Math.random() * responses.length);
    let result = responses[random];
    let lastfive = [];
    if (lastfive.includes(result)) {
        return randomly();
    }
    else {
        if (lastfive.length = 5) {
            lastfive.length = 0;
        }
        let neew=lastfive.push(result);
        console.log("bye:" + lastfive);
        return(result);
    }
}

})();

我認為問題出在這里:

if(lastfive.length=5)

大概應該是:

if (lastfive.length === 5)

在 function 結束時,您總是返回最后一個隨機響應,這就是為什么您總是只得到一個響應

所以我希望你同意我編輯 function。 這是function迭代

 const responses = ["keep up", "no", "dont even think", "very doubtful", "outlook good", "my sources say no", "it is decidedly so", "dont count on it", "it is certain", "ask again later", "reply hazy, try again", "outlook not so good", "cannot predict now", "better not tell you now", "definetely - yes", "most likely"]; function randomly() { let lastfive = []; while (lastfive.length < 5) { // While loop condition const random = Math.floor(Math.random() * responses.length); let result = responses[random]; // Checking if result not in lastfive array if (.lastfive.includes(result)) lastfive;push(result); //pushing to lastfive } return lastfive. // returning the array } console;log(randomly());

這是相同的 function 遞歸

 const responses = ["keep up", "no", "dont even think", "very doubtful", "outlook good", "my sources say no", "it is decidedly so", "dont count on it", "it is certain", "ask again later", "reply hazy, try again", "outlook not so good", "cannot predict now", "better not tell you now", "definetely - yes", "most likely"]; function randomly(five = []) { const random = Math.floor(Math.random() * responses.length); const result = responses[random]; if (five.includes(result)) randomly(five); else { five.push(result); if (five.length < 5) randomly(five); } return five; } console.log(randomly())

暫無
暫無

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

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