如何在 javascript 的数组中只检查选中的复选框

How to check for only checked checkboxes in an array in javascript

我正在使用 code.org 库。我正在尝试仅使用选中的复选框来 select 两支球队进行棒球比赛。目前我只能 select 1 个团队,但我需要有效地 select 两个团队,而不仅仅是去 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]);
});

假设我理解这个问题,您可以使用数组单独跟踪所选团队:

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(', ') + ".");
});

将选中的放在一个新数组中。

此外,请记住在让程序继续之前检查您是否已成功找到两个。

示例:

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]]);
    }
});