JavaScript Array.Splice()不会删除条目

时间:2019-03-07 11:53:45

标签: javascript node.js splice

如果某些条件为真,我试图从数组中删除一个条目,但是当我console.log对象数组时,该对象没有被删除,我很困惑为什么。我是否正确使用Splice()函数?

    var itemsProcessed;
people.forEach(async function(peep, index, object){

    var d = new Date();
    var currenttime = d.getTime();
    if (peep.endtime < currenttime){
        var rolesub = guild.roles.find(r => r.name == roleNameSub);

        var user2 = await client.fetchUser(peep.id);
        var member = await guild.fetchMember(user2);

        member.removeRole(rolesub);

        object.splice(index, 1);  //This seems to go wrong...

        console.log(peep.id + " Lost subscription!");
        user2.send("Your subscription ended!");

    }
    itemsProcessed++;
    if (itemsProcessed === object.length){
        SaveJson(people, "users.json");
    }
});    

2 个答案:

答案 0 :(得分:0)

您的问题是您要在迭代的同一数组上进行拼接,因此索引为何不正确。

您应该在迭代之前创建数组的副本,并通过获取要删除的元素的索引来从原始数组中删除元素,

arr.slice(0).forEach(function(item) {
    arr.splice(arr.indexOf(item), 1);
});

var arr = [{0:0},{i:1},{i:"test"},{i:"Something else"},{i:"Test"},5];
    
arr.slice(0).forEach(function(item) {

    if(item != 5)
        arr.splice(arr.indexOf(item), 1);
});
    
console.log(arr);

答案 1 :(得分:0)

您可以考虑和更改的一件事是,在迭代数组时,请勿在迭代时将其删除。只需将条目标记为删除即可。然后,完成后,滤除需要删除的内容。

例如:

people.forEach( (person,i) => {

   if( /* person needs to be removed from people */ ) {
       people[i] = null;  // use use array from 3rd parameter if you want to pass it in
   }
});

// then remove unwanted people

people = people.filter( person => person != null );

或者,如果您不想将 person 设置为null,则可以在对象中设置一个标志,而不是将其标记为删除。

示例:

people.forEach( (person,i) => {
   if( /* person needs to be removed from people */ ) {
       person.toBeDeleted = true;
   }
});

people = people.filter( person => person.toBeDeleted !== true );

也许更好或更干净的方法是不使用 forEach ,而仅使用 filter

示例:

    people = people.filter( p_person => {
         if( /* person stays */ ) {
             return true;
         } else {
             return false;
         }
    });