JavaScript数组拼接不改变指数 [英] Javascript Array Splice without changing the index

查看:99
本文介绍了JavaScript数组拼接不改变指数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

用户1连接和通过推送阵列中分配索引0。
用户2连接和通过推送阵列中分配索引1。

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

用户1断开,并通过剪接被删除。

User1 disconnects and is removed via splice.

现在用户2变为索引0。

NOW User2 becomes Index 0.

用户1重新连接,并通过推给出指数1。

User1 reconnects and is given Index 1 via push.

用户2断开和索引1被移除这是现在用户1。

User2 disconnects, and Index 1 is removed which is now User1.

这是当然的产生问题。

This is of course causing a problem.

所以我的问题是如何从数组中删除的项目而不改变其他元素的索引?我是在错误的轨道在这里?

So my question is how can I remove the item from the array without the index of the other elements changing? Am I on the wrong track here?

推荐答案

拼接(),为什么不设置值未定义

然后当你添加新用户,你可以通过扫描数组找到的第一个可用插槽中。

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

JavaScript数组是简单的项目名单 - 他们不键入到特定的键像你可能熟悉PHP中。所以,如果你想保持在阵列中的同一位置,不能删除其他物品 - 你需要让他们,只是将它们标记为空

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

这篇关于JavaScript数组拼接不改变指数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆