我目前正在设计一个程序,它将获取一个名称列表并将它们存储到3个不同的数组中,然后将所有名称添加到另一个单独的数组中,以便将它们分成两个不同的团队(另外两个数组)我到目前为止已经管理好了将所有内容正确地添加到最后两个数组中但是我有一个嵌套的IF,它应该在它达到一定的工作长度后停止将值添加到数组中。我无法弄清楚为什么这个IF..Else函数不起作用,只是想知道是否有人在使用array.length添加到数组时出现类似的问题
我已经包含了一个jsFiddle,因为涉及的代码相当多,我也必须归功于http://dreaminginjavascript.wordpress.com/2008/08/22/eliminating-duplicates/
对于他们的部分代码来说,这对于仅将单个记录添加到数组中非常有用。
http://jsfiddle.net/29q50yz0/
function randomFunction() {
document.getElementById("test4").innerHTML = team1.length;
if (team1.length <= 6 ) { //|| team2.length <= 5
for (index = 0; index < tier1.length; index++) {
randomNumber1 = Math.floor(Math.random() * 9);
if (randomNumber1 <= 4) {
team1.push(tier1[0]);
eliminateDuplicates(team1);
tier1.splice(0, 1);
} else {
team2.push(tier1[0]);
eliminateDuplicates2(team2);
tier1.splice(0, 1);
}
}
for (index = 0; index < tier2.length; index++) {
randomNumber1 = Math.floor(Math.random() * 9);
if (randomNumber1 <= 4) {
team1.push(tier2[0]);
eliminateDuplicates(team1);
tier2.splice(0, 1);
} else {
team2.push(tier2[0]);
eliminateDuplicates2(team2);
tier2.splice(0, 1);
}
}
for (index = 0; index < tier3.length; index++) {
randomNumber1 = Math.floor(Math.random() * 9);
if (randomNumber1 <= 4) {
team1.push(tier3[0]);
eliminateDuplicates(team1);
tier3.splice(0, 1);
} else {
team2.push(tier3[0]);
eliminateDuplicates2(team2);
tier3.splice(0, 1);
}
}
} else if (team1.length > 6) {
team2.concat(tier1, tier2, tier3);
document.getElementById("test2").innerHTML = team1;
document.getElementById("test3").innerHTML = team2;
} else if (team2.length > 6) {
team1.concat(tier1, tier2, tier3);
document.getElementById("test2").innerHTML = team1;
document.getElementById("test3").innerHTML = team2;
}
document.getElementById("test5").innerHTML = team1.length; }
请注意,即使有超过12条记录我正在寻找两支球队&#39;六,我正在寻找代码,当team1达到6的长度时,将剩余的记录添加到team2中,我已经包含了一些测试输出,以显示array.length正常工作,但JS中存在问题。
非常感谢提前
答案 0 :(得分:1)
这些功能有点混乱。看看我的方法:
如果团队未满,请检查随机数是否正确,或其他团队是否已满
function randomFunction() {
var allPlayers = [tier1, tier2, tier3];
for( var ti = 0; ti < allPlayers.length; ti++){ //foreach tier
for( var pi = 0; pi < allPlayers[ti].length; pi++) { //foreach player
randomNumber1 = Math.floor(Math.random() * 9);
if( team1.length < 6 && (randomNumber1 <= 4 || team2.length == 6)) { //team1 is not full or team2 is full
team1.push(allPlayers[ti][pi]);
}
else if( team2.length < 6 && (randomNumber1 > 4 || team1.length == 6)) { //team2 is not full or team1 is full
team2.push(allPlayers[ti][pi]);
}
}
}
//I don't know what this bit is doing :D
document.getElementById("test2").innerHTML = team1;
document.getElementById("test3").innerHTML = team2;
document.getElementById("team1").innerHTML = out1;
}