Array Design and Negative Numbers

I implemented a routing algorithm in javascript, but when I assign a negative one variable in an array, I get 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.

+3
source share
4 answers

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

var a = [-2];

The problem with the constructor Arrayis that when called with only one argument, this number is used as lengthfor a new array, for example:

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

, .

+11

!

var node = [6, 7];
+3

, .

+1
source

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 arrayLength; otherwise, if you use more than one, it will populate the array with these values.

However, as others have indicated, it is best to use a literal notation *

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

* Writing an array literally is a little bit faster than new Array(), but it is micro-optimization and not very important in most cases.

+1
source

Source: https://habr.com/ru/post/1746258/


All Articles