【问题标题】:Javascript: generating and storing random draws without replacementJavascript:无需替换即可生成和存储随机抽奖
【发布时间】:2019-04-01 03:34:52
【问题描述】:

我正在尝试使用 Javascript 创建一个数组,从数组中随机抽取两个 unique,然后将绘制的值分配给 HTML 表。我的方法是创建一个数组,随机抽取,创建一个没有绘制值的新数组,然后从新数组中随机抽取一次,作为一种无需替换的方式进行两次随机抽取。

我提供了一个最小的示例来说明我为实现此目的所做的工作,但它不起作用。我希望分配给 HTML 表的值最终是 foo 数组中的两个唯一值(例如“a”、“b”)。 这是否不起作用,因为下面的 value == bar_a 不会删除分配给 bar_a 数组的值,因为 bar_a 是一个数组,而不是数组的 value

虽然this post 已经解决了没有替换的绘图问题,但它没有提供使用字符串的示例或说明如何保存这两个数字,也不清楚为什么他们使用splice() 而不是filter()

    // Define array containing the set of values we'll randomly assign to A or B
    var foo = ["a", "b", "c", "d"];

    // Initialize variables to hold the value for A and B
    var bar_a=  [""];
    var bar_b=  [""];

    // Randomly draw from foo, save for A
    bar_a =foo[Math.floor(Math.random()*foo.length)];

    // Remove the drawn value from the array, create new array
    var foo_filtered = array.filter(function(value, index, arr){
        return value == bar_a;
        });

    // Randomly draw from foo_filtered, save for B
    bar_b = foo_filtered[Math.floor(Math.random()*foo_filtered.length)];

    // Assign attributes and values to their placeholders (a1, b1) in a HTML table
     document.getElementById("a1").innerHTML = bar_a;
     document.getElementById("b1").innerHTML = bar_b;

【问题讨论】:

  • 链接的答案是使用splice,因为它会更改原始数组,这正是您想要的,因为您不想要替换。看看这里:jsfiddle.net/Lrfhagyu

标签: javascript arrays random replace qualtrics


【解决方案1】:

您的过滤条件逻辑是倒退的。您需要等于bar_a的值。

您还需要将array.filter 更改为foo.filter

    // Define array containing the set of values we'll randomly assign to A or B
    var foo = ["a", "b", "c", "d"];

    // Initialize variables to hold the value for A and B
    var bar_a=  [""];
    var bar_b=  [""];

    // Randomly draw from foo, save for A
    bar_a =foo[Math.floor(Math.random()*foo.length)];

    // Remove the drawn value from the array, create new array
    var foo_filtered = foo.filter(function(value, index, arr){
        return value !== bar_a;
                  // ^^ not equal
        });

    // Randomly draw from foo_filtered, save for B
    bar_b = foo_filtered[Math.floor(Math.random()*foo_filtered.length)];

    // Assign attributes and values to their placeholders (a1, b1) in a HTML table
     document.getElementById("a1").innerHTML = bar_a;
     document.getElementById("b1").innerHTML = bar_b;
A: <span id="a1"></span>   B: <span id="b1"></span>

【讨论】:

  • array.filter 很好。这项工作,我接受了答案,但是这样做与使用拼接是否有权衡?使用拼接会是什么样子? Javascript 新手,通过拼凑来学习工作。
  • 取决于您是否需要再次执行所有操作,并且需要完整的原始数组。可以通过多种方式来简化这件事,但我只专注于让你有工作
猜你喜欢
  • 2012-11-27
  • 1970-01-01
  • 2012-06-14
  • 1970-01-01
  • 1970-01-01
  • 2013-07-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多