dimanche 23 mai 2021

.splice() from an array inside a For Loop and IF statement [duplicate]

I created an array "volunteerArray" and successfully created a function that adds elements to this array. Now I need a function to delete elements out of it. Below is my code and I've commented out other attempts I've made. Is my problem with my IF statement? Are there special rules for using IF inside of FOR loops?

var volunteerArray = [];

var deleteVolunteer = function () {
   
    var volunteerDelete = $("first_name").value + " " + $("last_name").value;

    for (i = 0; i < volunteerArray.length; i++) {
        if (volunteerArray(i) === volunteerDelete) {
            volunteerArray.splice(i, 1);
            i-- // do I need this? 
   
            // attempt 1: volunteerArray.remove(volunteerDelete);
            // attempt 2: volunteerArray.splice(i);
        }
    }
            
    //displays the volunteers and clears the add form
    //list will show the array elements without the spliced name
    displayVolunteers();
   
    // gets the delete form ready for next entry
    $("first_name").value = "";
    $("last_name").value = "";
    $("first_name").focus();
}

Aucun commentaire:

Enregistrer un commentaire