简体   繁体   中英

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

I was working on Magic 8 ball on my site and had to write the code on JS. Everything was fine until I decided to not get a random answer getting repeated 5 times. So basically, I wanna have an array that contains 5 last results that I have gotten.

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

})();

I think the problem is here:

if(lastfive.length=5)

Probably should be:

if (lastfive.length === 5)

At the end of the function, you're always returning the last random response it got thats why your always getting just one responese

So I hope you're okay with me editing the function. Here's the function iteratively

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

And this is the same function recursively

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM