|
Take a look at the following array definition:
var ar = new Array();
ar[0] = "Nothing is as easy as it looks.";
ar[1] = "Everything takes longer than you think.";
ar[2] = "Anything that can go wrong will go wrong.";
ar[3] = "Left to themselves, things tend to go from bad to worse.";
ar[4] = "Two wrongs are only the beginning.";
If you want to remove the second element of the array, you need to change the subscripts of the following elements:
var ar = new Array();
ar[0] = "Nothing is as easy as it looks.";
ar[1] = "Anything that can go wrong will go wrong.";
ar[2] = "Left to themselves, things tend to go from bad to worse.";
ar[3] = "Two wrongs are only the beginning.";
Not too difficult, is it? But if you try to do that with a 100-element array, you'll realize the problem. The solution is very simple. Since JavaScript arrays are zero-based (the first element has an index of 0), the index of the last element is one less than the length of the array. In other words, ar[ar.length - 1] always reflects the last element of the array. So the following set of statement populates our array in an elegant way:
var ar = new Array();
ar[ar.length] = "Nothing is as easy as it looks.";
ar[ar.length] = "Everything takes longer than you think.";
ar[ar.length] = "Anything that can go wrong will go wrong.";
ar[ar.length] = "Left to themselves, things tend to go from bad to worse.";
ar[ar.length] = "Two wrongs are only the beginning.";
Remember that the array's length property is dynamic. That is, its value changes as new elements are added to the array. If we want to get rid of the second element, we simply need to delete its definition:
var ar = new Array();
ar[ar.length] = "Nothing is as easy as it looks.";
ar[ar.length] = "Anything that can go wrong will go wrong.";
ar[ar.length] = "Left to themselves, things tend to go from bad to worse.";
ar[ar.length] = "Two wrongs are only the beginning.";
Similarly, we can add new elements anywhere in the middle of the array without updating the other elements.
People who read this tip also read these tips:
Look for similar tips by subject:
|