数组随机,没有匹配

时间:2016-06-16 11:03:28

标签: javascript arrays

我试图并排进行随机化的国旗,但我需要它不相互匹配,但我的情况更具体针对我发现的关于数组的解决方案:

function flags() {
var flagurls = ["ZPlo8tpmp/chi","cJBo8tpk6/sov","QyLo8tpkm/rus","68so8tpl4/pol","x1Ro8tplj/nor","TT3o8tplv/lit","IsZo8tpma/isr"];
var randomize = 'url("http://static.tumblr.com/zicio7x/'+flagurls[Math.floor(Math.random()*flagurls.length)]+'.png")';
var randomize2 = 'url("http://static.tumblr.com/zicio7x/'+flagurls[Math.floor(Math.random()*flagurls.length)]+'.png")';
document.getElementById("th1").style.backgroundImage = randomize;
document.getElementById("th2").style.backgroundImage = randomize2;

1 个答案:

答案 0 :(得分:0)

使用while循环:

function flags () {
  var flagurls = ["ZPlo8tpmp/chi","cJBo8tpk6/sov","QyLo8tpkm/rus","68so8tpl4/pol","x1Ro8tplj/nor","TT3o8tplv/lit","IsZo8tpma/isr"];
  var randomize = 'url("http://static.tumblr.com/zicio7x/'+flagurls[Math.floor(Math.random()*flagurls.length)]+'.png")';
  var randomize2 = randomize;

  while (randomize2 === randomize ) {
    randomize2 = 'url("http://static.tumblr.com/zicio7x/'+flagurls[Math.floor(Math.random()*flagurls.length)]+'.png")';
  }

  document.getElementById("th1").style.backgroundImage = randomize;
  document.getElementById("th2").style.backgroundImage = randomize2;
}

JSFiddle example