views:

106

answers:

4

I was implementing a routing algorithm in javascript, but when I assign a negative one variable in the array gives me this error: invalid array length.

var node = new Array()
node[0] = new Array(6,7)
node[1] = new Array(5,-4,8)
node[2] = new Array(-2) //Here, invalid array length

I do not know how to resolve this error.

+9  A: 

If you are trying to initialize an array that contains only a negative number, use the literal syntax:

var a = [-2];

The problem with the Array constructor is that when it is invoked only with only one argument, this number is used as the length of the new array, e.g.:

var b = new Array(5);
b.length; // 5

I recommend you to stick with the literal syntax to avoid those ambiguities.

CMS
That's bitten me before in some legacy code (no I won't accept blame!) where the list of numbers (big database keys, like credit card numbers but not exactly) was in a JSP variable. Strangely, whenever there was just one number in the list, the browser would get an "out of memory" error :-)
Pointy
This occurs if the only argument is an integer, It would work with a string.
Igor Pavelek
Thanks for the advice!
zizzamia
+3  A: 

Don't declare arrays that way!

var node = [6, 7];
Pointy
+1  A: 

It's because one integer argument sets the size of new Array.

Igor Pavelek
A: 

The array constructor documentation shows the following

var arr1 = new Array(arrayLength);
var arr2 = new Array(element0, element1, ..., elementN);

So, if you use only one parameter, it creates an array of arrayLength; otherwise, if you use more than one, it will populate the array with those values.

However, as others have pointed out, it is best use the literal notation *

var node = [
    [6, 7], 
    [5, -4 8],
    [-2]
];

* Array literal notation is slightly slightly faster than new Array(), but that's a micro optimization and not very important in most cases.

Justin Johnson