I thought I knew how to declare javascript arrays but in this script I am getting an infinite loop of undefined
elements in the array.
I declare three arrays of numbers, two of which have multiple values and one which has a single value.
I have a switch statement that assigns one of the three arrays to a new variable name cluster_array
When I run a 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";
Don't initialize arrays like that. Always do this instead:
var myarray = [value, value, value, ... ];
The "Array()" constructor is terribly designed. The single-argument form, when the argument is a number, is interpreted as a request to "initialize" an array with that many "empty" values. It's a pointless thing to do, so in general you're much better off using the array constant notation (as in my example above).
It doesn't seem to happen anymore in modern browsers, but I'd swear that there was a time that at least some browsers would actually allocate memory for the single-argument constructor, which was not really useful but dangerous to code that might accidentally pass in a single very large number.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With