【问题标题】:Losing the logic! Random unique numbers in javaScript失去逻辑! javaScript中的随机唯一数字
【发布时间】:2020-11-13 21:35:44
【问题描述】:

我需要编写一个函数来生成 0 到 60 之间的 6 个随机数,然后将它们存储在给定的数组中。此外,此函数无法在返回的数组中存储重复项。好吧,我在 StackOverflow(感谢 Shouvik)上找到了一个非常有用的答案,我将在下面展示。

但是,伙计们,我最有这种逻辑但错过了两个核心要素

  1. 我试图在没有第二个临时数组的情况下这样做
  2. 我不知道如何在数组中找到重复项

我知道我必须对数组进行 .indexOF 我知道我必须 .push 一个新值到数组

这是我在找到解决方案之前的代码:

function gerarDezenas() {
  let jogo = [];
  for (var i = 0;i < 6;i++) {
    jogo.push(Math.round(Math.random()*(1 , 60)+1));

    if (jogo.indexOf(jogo) == //clueless)c{
         .push() // ?? clueless either
    }
  }

  return jogo
}
console.log(gerarDezenas())

所以我发现我需要另一个 Array 和 if 条件来比较它

function gerarDezenas() {
  let jogo = []; 
  for (var i = 0; i < 6; i++) {
    var temp = Math.round(Math.random()*(1 , 60)+1);
    if (jogo.indexOf(temp) == -1) {
        jogo.push(temp)
    }
    else {
        i--;
    }
  }
  return jogo
}

代码现在可以按预期工作,但我并不真正理解它,问题就在这里!我不知道这些行在做什么:

if (jogo.indexOf(temp) == -1) {
    jogo.push(temp)
}
else {
      i--;
}

有人可以向我解释一下 if 和 else 在做什么吗?

如果你通读了这篇文章,非常感谢!

attached image please don't hate me

【问题讨论】:

    标签: javascript arrays random numbers


    【解决方案1】:

    如果 temp(随机数)不在 jogo 数组中(如果找不到值,indexOf 总是返回 -1)

    if (jogo.indexOf(temp) == -1)
    

    const arr = ["A","B","C"];
    console.log(arr.indexOf("D"));
    console.log(arr.indexOf("C"));

    然后将其添加到数组中

    jogo.push(temp)
    

    否则重做循环,希望得到一个不在 jogo 数组中的数字(-- 会抵消 ++)

     i--;
    

    let i = 5;
    i--
    i++
    console.log(i);

    【讨论】:

    • 很抱歉,但我仍然不明白如何确保数组内没有重复项!是 .indexOf 还是 -1 压缩?还是两者兼有?
    • @SamuelPantoja 语句 jogo.indexOf(temp) 如果 jogo 中存在 temp,则返回正值或 0,如果 temp 不存在,则返回 -1。所以jogo.indexOf(temp) == -1 说如果它不存在则插入,所以整个 if 块代码负责将唯一值插入到数组中。
    • @SamuelPantoja 两者兼而有之;当数组中已经存在 temp 时,循环无法前进,因此它会不断重复,直到 temp 不重复。最终,这不是一个有效的解决方案,因为它可能需要从 5 次尝试到 1,000,000 次以上(尽管后者不太可能)。
    【解决方案2】:
    /*Check whether array named jogo has the temp element inside it, if not add the temp element to jogo. */
    if (jogo.indexOf(temp) == -1){
        jogo.push(temp)
        }
    
    /*When you are inside this if else block the i's value must have been increased, now if
    temp is not being inserted because it's already there in the array, decrement i so that the if else block again runs with the same I what it was earlier before increment.
    */
        else {
          i--;
        }
    

    【讨论】:

      【解决方案3】:

      此代码循环遍历整个数组以检查随机数是否在数组内。但如果不是,它会输出 -1 表示当前随机数没有重复

      if (jogo.indexOf(temp) == -1)
      

      虽然这段代码只是反转循环,所以它取消了 i++。

      i--;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-05-03
        • 2014-01-14
        • 1970-01-01
        • 1970-01-01
        • 2013-03-13
        • 2014-05-29
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多