I was recently doctoring some code originally created by another developer, and found that there was some weird behaviour going on with the arrays in his code.
After doing some more research, I found that the developer was incorrectly deleting elements from arrays, which left holes in them and caused the length property to give out incorrect values.

So the classic javascript array. Declared like this:

var classic = [];
var classic2 = ['This','Is','An','Array'];

Now, say we wanted to remove the element ‘Is’ from classic2, some people may use this method:

delete classic2[1];

however, although it does remove the element, it’ll leave a hole in your array, and the length attribute of your array will stay the same. This is a mistake I’ve found in quite a few code samples.

alert(classic2.length);
delete classic2[1];
alert(classic2.length);

Both alert dialogs will show the same length. This is the wrong way to delete elements from an Array.
Here’s the right way, using the splice function:

alert(classic2.length);
var removed_element = classic2.splice(1,1);
alert(classic2.length);

This way, you see the length attribute working as intended, and splice will move elements after the removed element down one, so the consistency of the array is preserved.
Also, the Splice function returns the element or elements that have been removed from the array, so you can optionally catch that if you have use for it.
In the case that you’re working with a larger array or just generally don’t know the indexes of each element, you can do something like this:

classic2.splice(classic2.indexOf('Is'),1);
© 2012 The Life of a Dev Suffusion theme by Sayontan Sinha