开发者

Javascript splice not splicing

tl;dr; Even without my explanation one can look at the code below and the output and see something is fishy. Splice returns the index it spliced but the data remains in the array.

So I have an object that's keyed almost like an array (0,1,2,3...etc). Each object key has an array value. The array is an array of objects. Here's a simplified object that shows the basic structure I'm working with:

obj = {
    '1': [{},{},{},{}],
    '2': [{},{},{},{}],
    '3': [{},{},{},{}]
};

I have some code that needs to splice out one of the array indices (objects) from one of those arrays. This is the code, with console logging around everything (which I will show the output of below).

console.log(indices_to_remove);
for(j = 0; j < indices_to_remove.length; 开发者_C百科j++) {
    console.log("i: " + i)
    console.log('j: ' + j)
    console.log(this._index);
    console.log(this._index[i].splice(indices_to_remove[j], 1));
    console.log(this._index);
}

Notice on the second "console.log(this._index);" the spliced object is still part of the original array. I would assume that this._index[2] would now have one less item. Also, I should be splicing out index 0, yet it returns index 1.

Here's the output:

Javascript splice not splicing

So if anyone has any insight into what I might be doing wrong please speak up!

Thanks, Mike


There is a lot missing in the code that you are showing, so I had to do some guessing. I ran this code, and it works as expected:

var obj = {
    '1': [{},{},{},{}],
    '2': [{},{},{},{}],
    '3': [{},{},{},{}]
};

var indices_to_remove = [1];

var i = 1;
alert(indices_to_remove);
for(j = 0; j < indices_to_remove.length; j++) {
    alert("i: " + i)
    alert('j: ' + j)
    alert(obj[i]);
    alert(obj[i].splice(indices_to_remove[j], 1));
    alert(obj[i]);
}

However, you should consider looping backwards in the array of indexes to remove. When you have removed the first item, the second item is now the first item. If you then remove the second item, it's really the third item that you remove.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜