Javascript Array Splice而不更改索引

时间:2013-06-30 05:51:28

标签: javascript arrays indexing

我正在聊天并使用数组来保存用户。这是我的问题:

User1加入并通过push在数组中给出索引0。 User2通过push连接并在数组中给出索引1。

User1断开连接并通过splice删除。

现在User2成为索引0。

User1重新连接并通过推送获得索引1.

User2断开连接,删除索引1,现在是User1。

这当然会导致问题。

所以我的问题是如何在没有其他元素的索引改变的情况下从数组中删除该项?我在这里错了吗?

5 个答案:

答案 0 :(得分:13)

不是仅使用splice()从数组中删除项目,为什么不将值设置为nullundefined

然后,当您添加新用户时,您只需扫描数组即可找到第一个可用的插槽。

javascript数组只是项目列表 - 它们不像您在PHP中熟悉的那样键入特定键。因此,如果您想在数组中保持相同的位置,则无法删除其他项 - 您需要保留它们,并将它们标记为空。


您可以浏览以下内容:

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;
}

答案 1 :(得分:5)

另一种选择是使用javascript对象而不是数组。

这样的事情:

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"

您丢失了数组length属性,因此您必须自己跟踪最大用户数。

答案 2 :(得分:5)

使用delete代替splice

> a = ['1', '2', '3']
< Array [ "1", "2", "3" ]

> delete a[1]
< true

> a
< Array [ "1", undefined × 1, "3" ]

> a.length
< 3

答案 3 :(得分:0)

删除数组元素而不会面临重新索引问题

    var ind=[1,6]; //index positions of elements to remove
    var arr=['a','b','c','d','e','f','g']; // actual array
    var arr2 = arr.filter(function(item,index){
            if(ind.indexOf(index)== -1){
            return true;
    }});

现在arr2是==========&gt;&gt; [ '一个', 'C', 'd', 'E', 'F']

答案 4 :(得分:0)

我敢肯定,有多种解决方案都可以根据您的具体情况使用。我有一个使用React的项目,并且在将数组中的对象设置为undefined时遇到了类似的问题,因为在代码的其他地方,我会收到类似cannot find {key} of undefined的错误……与null一样。现在可以正常使用的..my解决方案是简单地重新创建整个数组,我可以这样做,因为它不是一个超长列表。根据您的描述进行了更改:

let newUsers = [];
users.forEach((u, i) => {
  if (u.isOnline) newUsers[i] = u;
});
this.setState({ users: newUsers });

...那种效果。就我而言,我有一份选定食谱的清单。如果该食谱已从整个食谱列表中删除,则会将其从选择列表中删除,所选索引会在其中指示它是哪个“菜谱”(即开胃菜,主菜,甜品),因此索引很重要。

另一种解决方案是将您的用户ID用作数组的索引。用户上线时,您可以设置onlineUsers[user.ID] = user //or true or user.Name or whatever

相关问题