Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
149 views
in Technique[技术] by (71.8m points)

Delete from array in javascript

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 another problem occurred when I deleted from that array. I use that object to populate a FlexiGrid. but when I delete an item from that object by following code, instead of delete that item , it sets to undefined :( and flexigrid did not accept it for input data.

for (var i = 0; i < Roomdata.length; i++) {

    if(Roomdata[i].id = X) {

        delete Roomdata[i];
        break;

    }
}                

For example, imagine I have 3 items in Roomdata like this :

{item1, item2, item3}

When I call this code to delete item2 , Roomdata object looks like this :

{item1, undefined, item3}

and this is a bad format to be accepted by flexigrid as input data

Is there any solution ?

Thanks every body and sorry about my bad syntax (I am new in English)

regards , Foroughi

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...