【发布时间】: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