我正在制作一个功能,其中随机索引被添加到具有for循环的数组中,值必须始终不同但不知何故有时(大约每10次调用函数)相同的值,即使我试图过滤相同的值来自answerId
- 数组并放置其余值unique
- 数组和检查已过滤unique
- 数组和原始answerId
- 具有相同长度的数组,如果{{1} -arrays length低于unique
- 数组长度,unique
s值将被更改。但是这些数组总是具有相同的长度,即使answerId
中有相同的值 - 数组并且运行不能传递给其余的for循环(那些for循环是相当一些黑客代码)。我做错了什么?对不起,如果我的英语技能不好。
answerId
答案 0 :(得分:1)
当我理解你的问题时,你想从数组中获得N个随机值,值应该是唯一的。你只需要将数组洗牌并从中获取前N个值。
答案 1 :(得分:1)
var array = [0, 1, 42, 17, 22, 3, 7, 9, 15, 35, 20],
unique = new Set;
while (unique.size < 4) {
unique.add(Math.floor(Math.random() * array.length));
}
console.log([...unique]); // indices
&#13;
否则,您可以使用哈希表。
var array = [0, 1, 42, 17, 22, 3, 7, 9, 15, 35, 20],
unique = {},
id = [],
i;
while (id.length < 4) {
i = Math.floor(Math.random() * array.length);
if (!unique[i]) {
id.push(i);
unique[i] = true;
}
}
console.log(id);
&#13;