3

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.

CharlesB
  • 86,532
  • 28
  • 194
  • 218
zizzamia
  • 241
  • 3
  • 9

4 Answers4

11

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.

Christian C. Salvadó
  • 807,428
  • 183
  • 922
  • 838
  • 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 May 19 '10 at 19:45
  • 1
    This occurs if the only argument is an integer, It would work with a string. – Igor Pavelek May 19 '10 at 19:47
3

Don't declare arrays that way!

var node = [6, 7];
Pointy
  • 405,095
  • 59
  • 585
  • 614
1

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

Igor Pavelek
  • 1,444
  • 14
  • 22
1

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
  • 30,978
  • 7
  • 65
  • 89