我希望将随机打印的字符串分组为两组。
以下是用于随机化字符串的JavaScript代码:
Array.prototype.shuffle= function(times){
var i,j,t,l=this.length;
while(times--){
with(Math){
i=floor(random()*l);j=floor(random()*l);
}
t=this[i];this[i]=this[j];this[j]=t;
}
return this;
}
var players=["Ben","Caleb","Alex","Ryder","Brad","Garret","Justin","John","Kevin"]
document.write(players.shuffle(200).join("<BR>") )
显然,目前打印订单是
NAME
NAME
NAME
NAME
NAME
NAME
NAME
NAME
NAME
但是我希望它是
NAME NAME
NAME NAME
NAME NAME
NAME NAME
NAME
我将如何做到这一点?
答案 0 :(得分:1)
for(var i=1; i<players.length+1; i+=2){
console.log(players[i-1]+" "+((players[i]!=undefined)?players[i]:""));
}
或
for(var i=0; i<players.length; i+=2){
console.log(players[i]+" "+((players[i+1]!=undefined)?players[i]:""));
}
你可以这样使用它:
Array.prototype.shuffle= function(times){
var i,j,t,l=this.length;
while(times--){
with(Math){
i=floor(random()*l);j=floor(random()*l);
}
t=this[i];this[i]=this[j];this[j]=t;
}
return this;
}
var players=["Ben","Caleb","Alex","Ryder","Brad","Garret","Justin","John","Kevin"]
players.shuffle(200);
for(var i=0; i<players.length; i+=2){
document.write(players[i]+" "+((players[i+1]!=undefined)?players[i+1]:"")+"<br>");
}
答案 1 :(得分:0)
只是评论:
非常不喜欢带有的,将在ECMAScript的未来版本中删除。它在这里使用是完全无偿的,考虑相当于:
i = Math.random() * l | 0;
j = Math.random() * l | 0;
关于以二人方式打印成员,请考虑:
// Only increment by 1 in the condition
for(var i=0, iLen=players.length; i<iLen; i++) {
// Second increment is in here
console.log(players[i] + " " + (++i in players? players[i] : ''));
}
因此,当测试3 in players
时,如果有3个项目(即索引0,1和2处的项目),它将返回false
并且不会打印任何内容。
你也可以这样做:
console.log(players[i] + " " + (++i < iLen? players[i] : ''));
答案 2 :(得分:0)
# first get your shuffled players
shuffled_players = players.shuffle(200)
# loop through them
for(var i=0; i<shuffled_players.length; i++){
document.write(shuffled_players[i]);
# put either a space or break
document.write(i%2 == 0 ? " " : "<BR>");
}