我正在使用code.org
库。我试图只使用选中的复选框为棒球比赛选择两支球队。目前我只能选择1个团队,但我需要选择两个团队,而不仅仅是去array
的下一个团队。我在JavaScript
中从未见过这样的问题。
onEvent("btnStart","click", function() {
var chkBoxs = ["Yankees","Boston","Astros"];
var index = 0;
while (index < chkBoxs.length && !getChecked(chkBoxs[index])) {
index++;
}
setScreen("game");
console.log("The Teams are: " + chkBoxs[index]+" And "+chkBoxs[index+1]);
});
答案 0 :(得分:0)
假设我理解了这个问题,您可以使用数组单独跟踪所选团队:
onEvent("btnStart","click", function() {
var chkBoxs = ["Yankees","Boston","Astros"];
var indexes = [];
for (var i =0; i < chkBoxs.length; i++) {
if (getChecked(chkBoxs[index]))) {
indexes.push(index); // store team index
}
}
setScreen("game");
console.log("The Teams are: " + chkBoxs[indexes[0]]+" And "+chkBoxs[indexes[1]]);
});
这也假设你总是有两个队。否则你必须以不同的方式处理最后一行。如果您只需要团队名称:
onEvent("btnStart","click", function() {
var chkBoxs = ["Yankees","Boston","Astros"];
var teams = [];
for (var i =0; i < chkBoxs.length; i++) {
if (getChecked(chkBoxs[index]))) {
teams.push(chkBoxs[index]); // store team name
}
}
setScreen("game");
console.log("The Teams are: " + teams.join(', ') + ".");
});
答案 1 :(得分:0)
将选定的数组放入新数组中。
此外,请记住在让程序继续之前检查是否已成功找到两个。
示例:
onEvent("btnStart","click", function() {
var chkBoxs = ["Yankees","Boston","Astros"];
var selected = [];
for (index = 0; selected.length < 2 && index < chkBoxs.length; index++) {
if (getChecked(chkBoxs[index])) { selected.push(index); }
}
setScreen("game");
if (selected.length == 2) {
console.log("The Teams are: " + chkBoxs[selected[0]] + " and " + chkBoxs[selected[1]]);
}
});