防止在数组中添加相同的随机值

时间:2017-01-18 09:53:36

标签: javascript arrays react-native

我正在制作一个功能,其中随机索引被添加到具有for循环的数组中,值必须始终不同但不知何故有时(大约每10次调用函数)相同的值,即使我试图过滤相同的值来自answerId - 数组并放置其余值unique - 数组和检查已过滤unique - 数组和原始answerId - 具有相同长度的数组,如果{{1} -arrays length低于unique - 数组长度,unique s值将被更改。但是这些数组总是具有相同的长度,即使answerId中有相同的值 - 数组并且运行不能传递给其余的for循环(那些for循环是相当一些黑客代码)。我做错了什么?对不起,如果我的英语技能不好。

answerId

2 个答案:

答案 0 :(得分:1)

当我理解你的问题时,你想从数组中获得N个随机值,值应该是唯一的。你只需要将数组洗牌并从中获取前N个值。

答案 1 :(得分:1)

您可以直接使用Set size属性来检查结果集的所需大小。



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;
&#13;
&#13;

否则,您可以使用哈希表。

&#13;
&#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;
&#13;
&#13;