Delete from array in javascript

后端 未结 3 1783
深忆病人
深忆病人 2020-11-30 14:08

3 hours ago, I asked a question in SO , about deleting a part of an object, so I linked this question to it:

delete a part of object in javascript

but now an

3条回答
  •  一个人的身影
    2020-11-30 14:19

    Walk through the array in reverse order, and use .splice to remove the element.
    You have to walk in the reverse order, because otherwise you end up skipping elements See below.

    for (var i = Roomdata.length-1; i >= 0; i--) {
        if (Roomdata[i].id == X) {
            Roomdata.splice(i, 1);
            break;
        }
    }
    

    What happens if you don't walk in the reverse order:

    // This happens in a for(;;) loop:
    // Variable init:
    var array = [1, 2, 3];
    var i = 0;
    
    array.splice(i, 1); // array = [2, 3]   array.length = 2
    // i < 2, so continue
    i++;  // i = 1    
    
    array.splice(i, 1); // i=1, so removes item at place 1: array = [2]
    // i < 1 is false, so stop.
    
    // array = [2]. You have skipped one element.
    

提交回复
热议问题