Jump to content

The JS Array parameters


brucemand

Recommended Posts

from the w3schools tutorial;

var myCars=new Array(); // regular array (add an optional integermyCars[0]="Saab";	   // argument to control array's size)myCars[1]="Volvo";myCars[2]="BMW";

there's a mention of optional integer to control the size.how would one use this ?i imagine it could be for error-trapping if you loop beyond the end of an array ?(since JS doesn't have the foreach() in PHP, but then there's always the array.length property , right ?)

Link to comment
Share on other sites

Passing a length creates that many dummy elements, and, as you said, establishes the length of the array before it has actual content. I've never found a use for this (though I suppose one is possible). In fact, I never use the new Array() constructor at all any more. JSON notation does the same job:var arr = [];

Link to comment
Share on other sites

Passing a length creates that many dummy elements, and, as you said, establishes the length of the array before it has actual content. I've never found a use for this (though I suppose one is possible). In fact, I never use the new Array() constructor at all any more. JSON notation does the same job:var arr = [];
yes, just for completions' sake, the other two ways possible from w3schools are;
2:var myCars=new Array("Saab","Volvo","BMW"); // condensed array3:var myCars=["Saab","Volvo","BMW"]; // literal array

i suppose it's a hold-over from the "old skool" days when an array's length had to be defined at declaration.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...