Javascript Array Splice without changing the index

前端 未结 5 1559
予麋鹿
予麋鹿 2020-12-17 14:20

I am working on a chat and using an array to hold the users. Here is my problem:

User1 joins and is given Index 0 in the array via push. User2 joins and is given Ind

5条回答
  •  无人及你
    2020-12-17 15:16

    Instead of removing the items from the array with splice(), why not just set the value to null or undefined?

    Then when you're adding a new user, you can just scan through the array to find the first available slot.

    javascript arrays are simply lists of items - they're not keyed to a specific key like you might be familiar with in PHP. So if you want to keep the same position in the array, you can't remove other items - you need to keep them, and just mark them as empty.


    You might scan through something like this:

    var users = [];
    function addUser(user) {
        var id = users.indexOf(null);
        if (id > -1) {
            // found an empty slot - use that
            users[id] = user;
            return id;
        } else {
            // no empty slots found, add to the end and return the index
            users.push(user);
            return users.length - 1;
        }
    }
    function removeUser(id) {
        users[id] = null;
    }
    

提交回复
热议问题