Cyr*_*rus 14 javascript arrays indexing
我正在聊天并使用数组来保存用户.这是我的问题:
User1通过push连接并在数组中给出Index 0.User2通过push连接并在数组中获得索引1.
User1断开连接并通过splice删除.
现在User2成为索引0.
User1重新连接并通过push给出索引1.
User2断开连接,删除索引1,现在是User1.
这当然会引起问题.
所以我的问题是如何在没有其他元素的索引改变的情况下从数组中删除项目?我在这里走错了路吗?
jcs*_*nyi 13
而不是从数组中删除项目splice(),为什么不将值设置为null或undefined?
然后,当您添加新用户时,您只需扫描阵列即可找到第一个可用插槽.
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;
}
Run Code Online (Sandbox Code Playgroud)
另一种选择是使用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"
Run Code Online (Sandbox Code Playgroud)
您丢失了数组length属性,因此您必须自己跟踪最大用户数.
用delete而不是splice.
> a = ['1', '2', '3']
< Array [ "1", "2", "3" ]
> delete a[1]
< true
> a
< Array [ "1", undefined × 1, "3" ]
> a.length
< 3
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
22903 次 |
| 最近记录: |