6

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";

test alert box

2
  • 1
    can you paste your switch statement ? Commented Mar 18, 2011 at 20:42
  • @moe it turns out that I was declaring the array the wrong way, per @Pointy's answer Commented Mar 18, 2011 at 20:46

1 Answer 1

14

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.

Sign up to request clarification or add additional context in comments.

2 Comments

The Array constructor can still be useful. Eg, it can be used to create loops where each value returned is accumulated in an array. So this.. new Array(4).fill().map((v, i) => i) will return the array [0, 1, 2, 3]
@Molomby yes that's good advice; this answer is over 6 years old, and that's forever in JavaScript time :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.