gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 21:11:22 25 4
gpt4 key购买 nike

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

getJSONData(){

var answerId = [null, null, null, null];
var length = Object.keys(Company.person).length;

for(var i = 0; i <= answerId.length - 1; i++){
answerId[i] = [Math.floor(Math.random() * length)]

}

let unique = Array.from(new Set(answerId))
console.log(unique.length)

if (unique.length < answerId.length){
for(var i = 0; i <= answerId.length - 1; i++){
answerId[i] = [Math.floor(Math.random() * length)]
}
console.log("new values 1")
unique = Array.from(new Set(answerId))

if (unique.length < answerId.length){
for(var i = 0; i <= answerId.length - 1; i++){
answerId[i] = [Math.floor(Math.random() * length)]
}
console.log("new values 2")
unique = Array.from(new Set(answerId))

if (unique.length < answerId.length){
for(var i = 0; i <= answerId.length - 1; i++){
answerId[i] = [Math.floor(Math.random() * length)]
}
console.log("new values 3")
unique = Array.from(new Set(answerId))

if (unique.length < answerId.length){
for(var i = 0; i <= answerId.length - 1; i++){
answerId[i] = [Math.floor(Math.random() * length)]
}
console.log("new values 4")
}
}
}
}

var personArray = [Company.person[answerId[0]].firstName + ' ' + Company.person[answerId[0]].lastName, Company.person[answerId[1]].firstName + ' ' + Company.person[answerId[1]].lastName, Company.person[answerId[2]].firstName + ' ' + Company.person[answerId[2]].lastName, Company.person[answerId[3]].firstName + ' ' + Company.person[answerId[3]].lastName];
return personArray;
}

最佳答案

你可以直接使用Setsize用于检查结果集所需大小的属性。

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

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

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);

关于javascript - 防止在数组中添加相同的随机值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41716168/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com