【问题标题】:Why new array in Javascript not getting pushed by the results I got?为什么 Javascript 中的新数组没有被我得到的结果推送?
【发布时间】:2021-03-12 20:48:35
【问题描述】:

我在我的网站上研究 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);
    }
}

})();

【问题讨论】:

  • 这个新数组只包含删除旧的最后一个结果。我哪里错了?
  • let lastfive=[]; 每次调用函数时都会创建一个新数组。

标签: javascript node.js arrays push


【解决方案1】:

我认为问题出在这里:

if(lastfive.length=5)

应该是:

if (lastfive.length === 5)

【讨论】:

    【解决方案2】:

    在函数结束时,你总是返回它得到的最后一个随机响应,这就是为什么你总是只得到一个响应

    所以我希望你同意我编辑这个函数。这是迭代的函数

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

    这是递归的同一个函数

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-17
      • 2016-05-17
      • 2021-04-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多