如何防止重复项被添加到数组中

时间:2018-09-16 01:42:54

标签: javascript arrays

var reservations = [];

function addReservation() {
    //Gets Input from textboxes. 
    var nameChosen = document.getElementById("txtName").value;
    var roomChosen = document.getElementById("selRoom").value; 

    //adds input into the array.
    reservations[reservations.length] = roomChosen + " ";
    reservations[reservations.length] = nameChosen + " ";

    //Gets input from radio button.
    for (i = 0; i < document.getElementsByName("Day[]").length; i++) {             
        if (document.getElementsByName("Day[]")[i].checked) {
            reservations.push(document.getElementsByName("Day[]")[i].value);
        }
    }
    for (i = 0; i < document.getElementsByName("Time[]").length; i++) {
        if (document.getElementsByName("Time[]")[i].checked) {
            reservations.push(document.getElementsByName("Time[]")[i].value);   
        }
    }                   
}

如果不能将时间和日期两次添加到阵列中,如何确保? 还是更简单,如何确保同一名称不能两次添加到阵列?

2 个答案:

答案 0 :(得分:0)

我认为您正在寻找一种方法,可以在打第一场比赛后退出for循环。一种实现方法是将i语句内的终止条件设置为if,这将退出循环。

//Gets input from radio button.
for (i = 0; i < document.getElementsByName("Day[]").length; i++) {             
    if (document.getElementsByName("Day[]")[i].checked) {
        reservations.push(document.getElementsByName("Day[]")[i].value);
        i = document.getElementsByName("Day[]").length
    }
}
for (i = 0; i < document.getElementsByName("Time[]").length; i++) {
    if (document.getElementsByName("Time[]")[i].checked) {
        reservations.push(document.getElementsByName("Time[]")[i].value);
        i = document.getElementsByName("Time[]").length
    }
}   

答案 1 :(得分:0)

测试项目是否首先在数组中

if (!item in array) { array.push(item); }