To splice or not to delete
I haven’t blogged much about programming recently due to being too busy… too busy to blog, not too busy to program.
This is just a swift post to highlight an important distinction that I haven’t seen mentioned anywhere else, and which recently I realised the siginificance of.
In javascript, what’s the difference between
delete my_array[i];
and
my_array.splice(i, 1);
Superficially they’re the same – they each remove the ith element from an array. But the crucial difference is that delete leaves a gap in the array, so there will no longer be an ith element – the array jumps straight from the (i-1)th to the (i+1)th element. But splice moves the (i+1)th element into the ith place in the array, and so on, shortening the array by one but moving everything along to fill the gap.
Why is this important?
If your code relies often on iterating through an array thus:
for(i=0;i<my_array.length;i++)
{
//some code
}
then any future iterations over the array will throw errors if you used delete to remove the ith element. But the iterations should still work if you used the splice method.
One note of caution, if you carry out
my_array.splice(i, 1);
within a loop over i, you should add the line
i--;
immediately after, to make sure you don’t miss out the next array element (which is now, of course, not in the (i+1)th place, but in the ith place).
Related posts:
- Remove text nodes functionHere’s a fairly useful function for when you’re using javascript...
- SortedOne of the problems I had to solve when writing...
- But it works for me!!!The lines of javascript below, included at the top of...
- Delicious, though not so easy to swallowFor a long time I’ve wanted to work with the...
- This literally changesYou should know that I’ve built up a lot of...
Tags: array, delete, javascript, splice