Javascript:生成和存储随机抽取而无需替换

标签 javascript arrays random replace qualtrics

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

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

同时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>

关于Javascript:生成和存储随机抽取而无需替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55447800/

相关文章:

java - 生成随机数量的字符

另一个 JavaScript 事件处理程序

javascript - 响应式 D3 圆环图

java - 如何连接具有相同键属性的对象列表

arrays - 在 Scala 中检索多维数组中有界元素的最大索引

python - (随机)替换字符串中 50% 的字符

string - 如何使用字符串作为 Golang 中 rand.Seed() 函数的输入?

javascript - 如何为 div 制作倒曲线或边框半径

javascript - 在一个div中制作超过4个顶点

arrays - cakephp 将树放入数组中