Domanda

I am making a small music player for embedding into a blog. It has a playlist functionality. I am having an issue where I cannot skip from the first song in the playlist to the last if you press previous on the first song. Instead of showing the last value it just shows 'undefined'. Does anyone know what might be causing this? Here is the JS Fiddle with my code in it, here are the two functions causing the issue:

function prevSong(){
    if (counter === 0){
        counter = songs.length;
    }
    else{
        counter = counter - 1;
    };
    changeSong();
};
function nextSong(){
    if (counter === songs.length){
        counter = 0;
    }
    else{
        counter = counter + 1;
    };
    changeSong();
};
È stato utile?

Soluzione

You're trying to go beyond the end of your array. Your array has 3 elements (0, 1, 2). songs.length == 3. songs[3] is invalid.

Use the following instead of what you have:

function prevSong()
{
    if (counter === 0)
    {
        counter = (songs.length-1);
    }
    else
    {
        counter = counter - 1;
    }
    changeSong();
}

function nextSong()
{
    if (counter === (songs.length-1))
    {
        counter = 0;
    }
    else
    {
        counter = counter + 1;
    }
    changeSong();
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top