문제

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();
};
도움이 되었습니까?

해결책

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();
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top