Javascript Array Splice 不改变索引
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17387571/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript Array Splice without changing the index
提问by Cyrus
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 Index 1 in the array via push.
User1 加入并通过推送在数组中获得索引 0。User2 加入并通过推送在数组中获得索引 1。
User1 disconnects and is removed via splice.
User1 断开连接并通过拼接移除。
NOW User2 becomes Index 0.
现在 User2 变为索引 0。
User1 reconnects and is given Index 1 via push.
User1 重新连接并通过推送获得索引 1。
User2 disconnects, and Index 1 is removed which is now User1.
User2 断开连接,索引 1 被删除,现在是 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?
所以我的问题是如何从数组中删除项目而不更改其他元素的索引?我在这里走错路了吗?
采纳答案by jcsanyi
Instead of removing the items from the array with splice()
, why not just set the value to null
or undefined
?
与其使用 删除数组中的项目splice()
,为什么不将值设置为null
或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.
javascript 数组只是项目列表 - 它们不像您在 PHP 中可能熟悉的那样以特定键为键。所以如果你想在数组中保持相同的位置,你不能删除其他项目 - 你需要保留它们,并将它们标记为空。
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;
}
回答by Yann Dìnendal
Use delete
instead of splice
.
使用delete
代替splice
。
> a = ['1', '2', '3']
< Array [ "1", "2", "3" ]
> delete a[1]
< true
> a
< Array [ "1", undefined × 1, "3" ]
> a.length
< 3
回答by jcsanyi
Another option is to use a javascript object instead of an array.
另一种选择是使用 javascript 对象而不是数组。
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.
length
但是,您丢失了数组属性,因此您必须自己跟踪最大用户数。
回答by vinay kumar jangam
remove array elements without facing re-indexing problem
删除数组元素而不面临重新索引问题
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;
}});
now arr2 is ==========>> ['a','c','d','e','f']
现在 arr2 是 ==========>> ['a','c','d','e','f']
回答by Michael Aaron Wilson
I'm sure there is a variety of solutions that work depending on your specific context. I have a project using React and was having a similar issue when setting an object in an array to undefined because elsewhere in the code I would get an error like cannot find {key} of undefined
...the same happened with null
...my solution that now works fine is to simply recreate the whole array, which I can do in my case because it is not a super long list. Altered to fit your description:
我确信有多种解决方案可以根据您的具体情况进行工作。我有一个使用 React 的项目,并且在将数组中的对象设置为 undefined 时遇到了类似的问题,因为在代码的其他地方我会得到一个错误,例如cannot find {key} of undefined
......同样的情况null
......我现在工作正常的解决方案是只需重新创建整个数组,在我的情况下我可以这样做,因为它不是一个超长的列表。已更改以适合您的描述:
let newUsers = [];
users.forEach((u, i) => {
if (u.isOnline) newUsers[i] = u;
});
this.setState({ users: newUsers });
...something to that effect. In my case I have a list of selected recipes. If the recipe was deleted from the overall list of recipes, this removes it from the list of selections, where the selected index indicates which 'course' it is (i.e. Appetizer, Entree, Dessert) so the index matters.
……那种效果。就我而言,我有一份精选食谱清单。如果菜谱从菜谱的整体列表中删除,这会将其从选择列表中删除,其中所选索引指示它是哪个“课程”(即开胃菜、主菜、甜点),因此索引很重要。
Another solution could be to use your Users' ID as the index of the array. When a user comes online you can set onlineUsers[user.ID] = user //or true or user.Name or whatever
另一种解决方案是使用您的用户 ID 作为数组的索引。当用户上线时,您可以设置onlineUsers[user.ID] = user //or true or user.Name or whatever