简体   繁体   English

Javascript数组最佳实践使用[]而不是新数组?

[英]Javascript array best practice to use [] instead of new array?

I read at many tutorials that the current best practices to create a new javascript array is to use 我在许多教程中读到了创建新javascript数组的当前最佳实践

var arr = [] 

instead of 代替

var arr = new Array()

What's the reasoning behind that? 这背后的原因是什么?

It might be because the Array object can be overwritten in JavaScript but the array literal notation cannot. 这可能是因为Array对象可以在JavaScript中覆盖,但是数组文字表示法不能。 See this answer for an example 请参阅此答案以获取示例

Also note that doing: 还要注意做:

var x = [5];

Is different than doing: 与做的不同:

var x = new Array(5);

The former creates an initializes an array with one element with value of 5. The later creates an initializes an array with 5 undefined elements. 前者创建一个初始化数组,其中一个元素的值为5.后者创建一个初始化一个包含5个未定义元素的数组。

It's less typing, which in my book always wins :-) 它的打字较少,在我的书中总是胜出:-)

Once I fixed a weird bug on one of our pages. 一旦我在我们的一个页面上修复了一个奇怪的错误。 The page wanted to create a list of numeric database keys as a Javascript array. 该页面想要创建一个数字数据库键列表作为Javascript数组。 The keys were always large integers (a high bit was always set as an indicator). 键总是大整数(高位始终设置为指示符)。 The original code looked like: 原始代码看起来像:

 var ids = new Array(${the.list});

Well, guess what happened when the list had only one value in it? 那么,猜猜当列表中只有一个值时发生了什么?

 var ids = new Array(200010123);

which means, "create an array and initialize it so that there are 200 million empty entries". 这意味着,“创建一个数组并初始化它,以便有2亿个空条目”。

Usually an array literal(var a=[1,2,3] or a=[]) is the way to go. 通常,数组文字(var a = [1,2,3]或a = [])是要走的路。

But once in a while you need an array where the length itself is the defining feature of the array. 但偶尔你需要一个数组,其长度本身就是数组的定义特征。

var A=Array(n) would (using a literal) need two expressions- var A = Array(n)将(使用文字)需要两个表达式 -

var A=[]; var A = []; A.length=n; 则为a.length = N;

In any event, you do not need the 'new' operator with the Array constructor, not in the way that you DO need 'new' with a new Date object, say. 无论如何,你不需要使用Array构造函数的'new'操作符,而不需要使用新的Date对象需要'new'的方式。

To create Array without Length 创建没有长度的数组

var arr = [];

To create Array with Length more dynamically 更动态地创建具有长度的数组

var arr;
( arr = [] ).length = 10;  // 10 is array length

To create Array with Length less dynamically 创建具有较小动态长度的数组

var arr = [];
arr.length = 10;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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