我正在尝试使用 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/