Javascript Array Splice without changing the index

前端 未结 5 1565
予麋鹿
予麋鹿 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:01

    Another option is to use a javascript object instead of an array.

    Something like this:

    var users = {};
    
    users[1] = 'user 1';
    users[2] = 'user 2';
    
    delete users[1];
    alert(users[2]);        // alerts "user 2"
    alert(typeof users[1]); // alerts "undefined"
    

    You lose the array length property though, so you'll have to keep track of your max user number yourself.

提交回复
热议问题