0

我正在使用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]);
});
4

2 回答 2

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(', ') + ".");
});
于 2017-03-30T13:25:50.677 回答
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]]);
    }
});
于 2017-03-30T13:42:14.140 回答