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.
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:
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; 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: