我编写了一个函数,它生成一个包含 10 个随机生成的唯一值的数组。
我想扩展它以便不包含某些值。
这是我的代码:
let excludedValues = [20,32,40,46,64,66,14,30,34];
let randomArray = [];
while(randomArray.length < 10){
let randomValue = Math.floor(Math.random() * 100) + 1;
let valueNotAllowed = excludedValues.includes(randomValue);
while (valueNotAllowed) {
randomValue = Math.floor(Math.random() * 100) + 1;
valueNotAllowed = excludedValues.includes(randomValue);
}
if(randomArray.indexOf(randomValue) === -1) randomArray.push(randomValue);
}
console.log(randomArray);
它创建了一个长度为 10 的数组,其值在 1 到 100 之间,但 ii 仍然包含 excludedValues
数组中的值
我怎样才能使这些值不在数组中结束
提前致谢
最佳答案
作为已发布答案的替代方案,您可以使用 Set
function getUniqueRandomValues(exclusion = []) {
// By definition, values inside of a Set are unique
const randomArray = new Set();
do {
const randomValue = Math.floor(Math.random() * 100) + 1;
// If the exclusion rule is satisfied push the new value in the random array
if (!exclusion.length || !exclusion.includes(randomValue)) {
randomArray.add(randomValue);
}
} while (randomArray.size < 10);
return Array.from(randomArray);
}
console.log(getUniqueRandomValues([20, 32, 40, 46, 64, 66, 14, 30, 34]));
关于javascript - 如何从随机生成的数组中排除某些值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60170711/