Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
397 views
in Technique[技术] by (71.8m points)

javascript - 声明JavaScript数组时,“ Array()”和“ []”之间有什么区别?(What’s the difference between “Array()” and “[]” while declaring a JavaScript array?)

What's the real difference between declaring an array like this:

(声明这样的数组之间的真正区别是什么:)

var myArray = new Array();

and

(和)

var myArray = [];
  ask by Amr Elgarhy translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There is a difference, but there is no difference in that example.

(有所不同,但在该示例中没有区别。)

Using the more verbose method: new Array() does have one extra option in the parameters: if you pass a number to the constructor, you will get an array of that length:

(使用更冗长的方法: new Array()在参数中确实有一个额外的选择:如果将数字传递给构造函数,则将获得该长度的数组:)

x = new Array(5);
alert(x.length); // 5

To illustrate the different ways to create an array:

(为了说明创建数组的不同方法:)

var a = [],            // these are the same
    b = new Array(),   // a and b are arrays with length 0

    c = ['foo', 'bar'],           // these are the same
    d = new Array('foo', 'bar'),  // c and d are arrays with 2 strings

    // these are different:
    e = [3]             // e.length == 1, e[0] == 3
    f = new Array(3),   // f.length == 3, f[0] == undefined

;

Another difference is that when using new Array() you're able to set the size of the array, which affects the stack size.

(另一个区别是,使用new Array()您可以设置数组的大小,这会影响堆栈的大小。)

This can be useful if you're getting stack overflows ( Performance of Array.push vs Array.unshift ) which is what happens when the size of the array exceeds the size of the stack, and it has to be re-created.

(如果您遇到堆栈溢出( Array.push与Array.unshift的性能 )(当数组的大小超过堆栈的大小并且必须重新创建它时会发生这种情况),这将很有用。)

So there can actually, depending on the use case, be a performance increase when using new Array() because you can prevent the overflow from happening.

(因此,实际上,根据使用情况,使用new Array()可以提高性能,因为可以防止溢出的发生。)

As pointed out in this answer , new Array(5) will not actually add five undefined items to the array.

(如该答案所指出的, new Array(5)实际上不会向该数组添加五个undefined项。)

It simply adds space for five items.

(它只是增加了五个项目的空间。)

Be aware that using Array this way makes it difficult to rely on array.length for calculations.

(请注意,以这种方式使用Array使得难以依靠array.length进行计算。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...