最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Array construction and negative numbers - Stack Overflow

programmeradmin2浏览0评论

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.

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.

Share Improve this question edited May 4, 2012 at 23:33 CharlesB 90.4k29 gold badges201 silver badges228 bronze badges asked May 19, 2010 at 19:38 zizzamiazizzamia 2413 silver badges9 bronze badges 0
Add a ment  | 

4 Answers 4

Reset to default 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 remend you to stick with the literal syntax to avoid those ambiguities.

Don't declare arrays that way!

var node = [6, 7];

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

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.

发布评论

评论列表(0)

  1. 暂无评论