簡體   English   中英

Javascript Array Splice 不改變索引

[英]Javascript Array Splice without changing the index

我正在聊天並使用數組來容納用戶。 這是我的問題:

User1 加入並通過推送在數組中獲得索引 0。 User2 加入並通過推送在數組中獲得索引 1。

User1 斷開連接並通過拼接移除。

現在 User2 變為索引 0。

User1 重新連接並通過推送獲得索引 1。

User2 斷開連接,索引 1 被刪除,現在是 User1。

這當然會引起問題。

所以我的問題是如何在不改變其他元素的索引的情況下從數組中刪除該項目? 我在這里走錯路了嗎?

與其使用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;
}

使用delete而不是splice

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

> delete a[1]
< true

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

> a.length
< 3

另一種選擇是使用 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屬性,因此您必須自己跟蹤最大用戶數。

我相信有多種解決方案可以根據您的具體情況進行工作。 我有一個使用 React 的項目,並且在將數組中的對象設置為 undefined 時遇到了類似的問題,因為在代碼的其他地方我會得到一個錯誤,比如cannot find {key} of undefined ...同樣的情況發生在null ...我現在工作正常的解決方案是簡單地重新創建整個數組,在我的情況下我可以這樣做,因為它不是一個超長的列表。 已更改以適合您的描述:

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

刪除數組元素而不面臨重新索引問題

    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 是 ==========>> ['a','c','d','e','f']

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM