mardi 5 mai 2020

Updating an array based on randomly generated index

I'm very new to Javascript and jQuery. I'm trying to create a film list that will randomly pick an item from the list, post the result, and remove the item from the original list. It uses text input, .push and .append to keep track of the list and update an array of matching text. My thinking was that I would use an array that matches the ul to generate a random index number from its length and then use the number to remove the li from the ul by index. The basic idea is working. My issue is that every time it selects an item from the list, the item it removes from the array is different than the item it posts and removes from the ul. The parts seem to work fine separately until I run them in a function together tied to a button.

Here is the code I'm using. The watchList array is populated with a .push whenever text is accepted to update the ul. I've checked and the index for both match up.

function randomShow(){
var r = Math.floor(Math.random() * watchList.length);
for(var i = 0; i < watchList.length; i++){
    if(i === r) {
            alert(watchList[i]);
            watchList.splice(watchList.indexOf[i],1);
            $("li").eq(i).remove();

        }
    }

}



Aucun commentaire:

Enregistrer un commentaire