Javascript:生成并存储随机抽奖,无需更换

Javascript: generating and storing random draws without replacement

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

我提供了一个最简单的示例来说明我为实现此目的所做的工作,但它不起作用。我希望分配给 HTML table 的值最终是 foo 数组中的两个唯一值(例如 "a"、"b")。 这是否不起作用,因为下面的值 == 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;

你的过滤条件逻辑倒退了。您想要 等于 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>