1

I have created a script to add people to an ignore list, however once I've added them there is a problem with deleting them. If I remove one user, from the array I can still add users to the ignore list. If I remove both people from the ignore list, I cannot add any more. I have a feeling it's because "ignored_users" is no longer an array?

I add people to the ignore list using this code: {all vars are set, and works}

add_to_list = {
    "username" : username,
    "date_added" : "\"" + day + "/" + month + "/" + year + "\"", 
    "description" : desc
};
ignored_users.push(add_to_list);
localStorage["ignore_list"] = JSON.stringify(ignored_users);

The array starts looking like this:

ignored_users = [{"username":"test1","date_added":"\"4/7/2013\"","description":""},{"username":"test2","date_added":"\"4/7/2013\"","description":""}]

The remove from array code looks like this:

$.each(ignored_users, function(i, person) { 
    if(person.username === username)
    {
        delete ignored_users[i];
        localStorage["ignore_list"] = JSON.stringify(ignored_users);
    }
}
4

3 回答 3

1

而是使用本机循环spliceeach在过去使用时,从您正在迭代的数组中删除一个元素给我带来了问题。尝试这个:

ignored_users = [{
    "username": "test1",
    "date_added": "\"4/7/2013\"",
    "description": ""
}, {
    "username": "test2",
    "date_added": "\"4/7/2013\"",
    "description": ""
}]

var username = "test1";
for (var i = 0; i < ignored_users.length; i++) {
    if (ignored_users[i].username === username) {
        ignored_users.splice(i, 1);
        localStorage["ignore_list"] = JSON.stringify(ignored_users);
    }
}

示例小提琴

于 2013-07-04T14:49:17.050 回答
0

delete ignored_users[i];实际上不会做你想做的事,它会使元素 #i 未定义,但不会缩小数组。

你需要使用splice()方法。从数组中删除元素#i:

array.splice(i, 1)
于 2013-07-04T14:50:53.727 回答
0

您正在使用delete从数组中删除元素,但这不会更新数组的索引,它设置为undefined您要删除的索引。因此,当您再次重新运行代码时,person将是未定义的。尝试:

$.each(ignored_users, function(i, person) { 
    if(person && person.username === username)
    {
        delete ignored_users[i];
        localStorage["ignore_list"] = JSON.stringify(ignored_users);
    }
}

您还可以在此处查看从数组中删除元素的其他形式。

于 2013-07-04T14:51:54.100 回答