简体   繁体   中英

Array construction and negative numbers

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.

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, eg:

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

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

不要那样声明数组!

var node = [6, 7];

这是因为一个整数参数设置了新数组的大小。

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM