使用javascript从数组中随机获取集合

时间:2014-12-18 10:04:03

标签: javascript

var ramdomCharacters = ["a", "c", "z", "d", "f", "i", "u"];

我想从随机字符中随机提取一个子集,该字符具有随机长度和非重复项。像这样:

subset = ["c", "f", "i"]

subset = ["a", "u"]

2 个答案:

答案 0 :(得分:1)

一种可能的方法是随机化数组并提取第一个n元素:

var randomCharacters = ['a', 'c', 'z', 'd', 'f', 'i', 'u'];

var clone = [].slice.call(randomCharacters),   // clone not to alter the original
    n = Math.random() * clone.length + 1,      // `n` may vary upon your needs
    subset = clone.sort(function() {
        return 0.5 - Math.random();            // shuffle array
    }).slice(0, n);                            // slice first `n` elements

console.log(subset);

答案 1 :(得分:0)

你可以尝试:

var randomCharacters = ['a', 'c', 'z', 'd', 'f', 'i', 'u'];
var subset=[];
while (randomCharacters.length>0)
  {
    dummy=randomCharacters.pop();
    if (Math.random()<0.5) subset.push(dummy);
  }
document.write(subset);

这与前一个答案的不同之处在于:(1)randomCharacters最终为[],(2)&#39;子集&#39;的最终值。可能是[]和(3),虽然是随机的,但是&#39;子集&#39;的顺序。实际上与randomCharacters的逆序相同。