javascript - 如何从随机生成的数组中排除某些值

标签 javascript node.js

我编写了一个函数,它生成一个包含 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/

相关文章:

node.js - 在 ES6 中导入 DocumentReference

javascript - Bit.dev 无法添加 2 个具有相同 ID 的组件

javascript - KineticJS 的 iOS 滚动/捏缩放问题

node.js - 包 react 不满足它的 sibling

node.js - 在Angular + Electron应用程序: Module parse failed: Unexpected character中使用Better-sqlite3

linux - 对 Node JS 中的 NPM 进行故障排除

javascript - 从 ES6 javascript 中的字符串动态创建方法(非浏览器)

c# - 自动编码文本输入的策略?

javascript - 如何测试默认导出的js文件?

javascript - React @flow 避免重复类型