The javascript array contains only undefined after initialization, not the given values

I thought I knew how to declare javascript arrays, but in this script I get an infinite loop of undefined elements in the array.

I declare three arrays of numbers, two of which have multiple values ​​and one value that has one value.

I have a switch statement that assigns one of the three arrays a new variable name cluster_array

When I run the for loop through cluster_array , I get an infinite loop and every element if undefined

What am I missing?

 <script type="text/javascript"> var ga_west_cluster = new Array(10,11,12,14,74,75,76,77,78,79,80,81,82,83,85,86,87,88,89,90,91,92,295,296); // original bad array var ga_east_cluster = new Array(84); // added an extra (dummy) value and it works fine var ga_east_cluster = new Array(1,84); var sc_cluster = new Array(93,94,95,96,97,98,99,100,101,102,103); </script> 

Here is the alert text:

 var test_message = "cluster data\n"; for(var k=0;k<cluster_array.length;k++) test_message += "value: "+cluster_array[k]+"\n"; 

test alert box

+6
javascript arrays undefined
source share
1 answer

Do not initialize such arrays. Always do this instead:

 var myarray = [value, value, value, ... ]; 

The constructor of "Array ()" is terribly designed. A form with one argument, when the argument is a number, is interpreted as a request to "initialize" an array with many "empty" values. This is a pointless thing, so in general you are much better off using constant array notation (as in my example above).

In modern browsers, this does not seem to happen anymore, but I would swear that there was a time when at least some browsers actually allocated memory for the constructor with one argument, which was not very useful, but dangerous for code that might accidentally go into one very large amount.

+14
source share

All Articles