Reputation: 241
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.
Upvotes: 3
Views: 4178
Reputation: 31300
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.
Upvotes: 1
Reputation: 1444
It's because one integer argument sets the size of new Array.
Upvotes: 1
Reputation: 827218
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.
Upvotes: 11