Javascript,填充数组,没有重复的字符串

时间:2018-04-27 23:45:48

标签: javascript arrays duplicates

我在python中创建了这个程序,并希望在Javascript中实现相同的结果。不幸的是,我正在努力争取最后一件事,那就是一个人被添加到最后的驳船中。数组,我不希望它们再次被使用,因为在最终数组中我不能有重复的人。关于我失踪的任何建议。再次在python中,我把它钉了下来,但javascript我似乎无法让重复停止。也可以向整个程序提供任何帮助。谢谢!



var a = ['mike', 'dan', 'christian', 'trevor', 'jess'];
var b = ['mike', 'sarah', 'kenny', 'trevor', 'dennis', 'jeff'];
var c = ['pavel', 'sean', 'kenny', 'chris', 'lucas', 'elizibeth'];
var d = ['sarah', 'sean', 'allison', 'jules', 'trevor', 'jeff'];
var e = ['sarah', 'sean', 'jules', 'trevor', 'chris'];
var f = ['val', 'kirk', 'pavel', 'sean', 'kenny', 'chris', 'lucas', 'elizibeth'];
var g = ['mike', 'sarah', 'kenny', 'trevor', 'dennis', 'jeff'];
var h = ['val', 'sarah', 'allison', 'kenny', 'trevor', 'lucas'];


function randomChoice(list) {
  return (list[Math.floor(Math.random() * list.length)]);
};
var barge = []
while (barge.length < 8) {
  var barge = []
  var used = []
  var alpha = randomChoice(a);
  if (!(alpha in used)) {
    barge.push(alpha);
    used.push(alpha);
    var bravo = randomChoice(b);
    if (!(bravo in used)) {
      barge.push(bravo);
      used.push(bravo);
      var charlie = randomChoice(c);
      if (!(charlie in used)) {
        barge.push(charlie);
        used.push(charlie);
        var delta = randomChoice(d);
        if (!(delta in used)) {
          barge.push(delta);
          used.push(delta);
          var echo = randomChoice(e);
          if (!(echo in used)) {
            barge.push(echo);
            used.push(echo);
            var foxtrot = randomChoice(f);
            if (!(foxtrot in used)) {
              barge.push(foxtrot);
              used.push(foxtrot);
              var golf = randomChoice(g);
              if (!(golf in used)) {
                barge.push(golf);
                used.push(golf);
                var hotel = randomChoice(h);
                if (!(hotel in used)) {
                  barge.push(hotel);
                  used.push(hotel);
                }
              }
            }
          }
        }
      }
    }
  }
};
console.log(barge);
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:3)

一个简单的解决方案是使用Set

var set = new Set(); 
set.add('mike');
set.add('dan');
...

集合包含唯一值,因此您(最多)每个名称都有一个实例。