Vardan Betikyan
Vardan Betikyan

Reputation: 394

Javascript - First element of array returns Undefined

I have a weird situation, where array[0] is returning Undefined, even if there are elements in the array.

Any ideas?

var PLAYER_LIST = [];

function refresh(data){
    var players = data.players;
    for(var p in players){
        var newPlayer = players[p];
        var id = newPlayer.id;
        
        if(PLAYER_LIST[id] == undefined){
            PLAYER_LIST[id] = createPlayer(newPlayer);
        }
        var player = PLAYER_LIST[id];
        
        player.position = newPlayer.position;
        player.angle    = newPlayer.angle;
        player.controls = newPlayer.controls;
        player.speed    = newPlayer.speed;
        player.update   = 0;
    }

    console.log(PLAYER_LIST[0]); //returns Undefined
    console.log(PLAYER_LIST); //returns entire array (works normally)
    console.log(PLAYER_LIST.length); //returns 0 (when it should return 1)
}

refresh(obj); //obj full of new player info

console.log(PLAYER_LIST) returns

[3oPNoqkvaBtAYPGrAAAr: {…}]
3oPNoqkvaBtAYPGrAAAr: {id: "3oPNoqkvaBtAYPGrAAAr", animation: 0, 
animationCountTotal: 5, animationCount: 4, saveAngle: 0, …}
length: 0
__proto__: Array(0)

Upvotes: 0

Views: 1111

Answers (1)

Jim Vercoelen
Jim Vercoelen

Reputation: 1077

Your list is an array, not an object, so you won't be able to get the player from the list using players['player-id']

You don't need to iterate over the entire list, just simply detect whether or not the player exists, when that's not the case: create one and add it to your list, otherwise update the existing player in the list with the new player data.

Try something like this:

<!DOCTYPE html>
    <body>
        <script>
            var PLAYER_LIST = [{
                id: 1,
                name: 'john do'
            }];

            function createPlayer(newPlayer) {
                // what ever it is you do here..
                return newPlayer;
            }

            function refresh(data) {
                const playerIndex = PLAYER_LIST.findIndex(p => p.id === data.id);

                if (playerIndex === -1) {
                    const newPlayer = createPlayer(data);
                    PLAYER_LIST.push(newPlayer);
                } else {
                    PLAYER_LIST[playerIndex] = data;
                }
            }

            refresh({ name: 'jane do' }); // I don't exist, create me
            refresh({ id: 1, name: 'changed' }); // I exist, update me
            console.log('Refreshed list: ', PLAYER_LIST);
        </script>
    </body>
</html>

Upvotes: 1

Related Questions