spacer
Yehuda Shiran December 2, 1999
Populating Arrays
Tips: December 1999

Yehuda Shiran, Ph.D.
Doc JavaScript

Developer News
Microsoft Shows Off Silverlight 4, IE9 Plans
Metasploit Expands Vulnerability Test Framework
HyperCard Reborn?

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:

internet.commediabistro.comJusttechjobs.comGraphics.com

Search:

WebMediaBrands Corporate Info

Legal Notices, Licensing, Permissions, Privacy Policy.
Advertise | Newsletters | Shopping | E-mail Offers | Freelance Jobs

webref The latest from WebReference.com Browse >
Rolling Out Your Own HTML Application Version Control · HTML 5: Client-side Storage · Working with Ajax Server Extensions
Sitemap · Experts · Tools · Services · Email a Colleague · Contact FREE Newsletters 
 The latest from internet.com
Wi-Fi Product Watch, November 2009 · Chip Market Recovering From '08 Collapse · Low-Cost Tools to Kickstart Your New Business