在 Javascript 中声明数组时要遵循的最佳实践是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11500492/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What are the best practices to follow when declaring an array in Javascript?
提问by Naigel
When I need to declare a new array I use this notation
当我需要声明一个新数组时,我使用这种表示法
var arr = new Array();
But when testing online, for example on jsbin, a warning signals me to "Use the array literal notation []."
但是当在线测试时,例如在jsbin 上,一个警告提示我“使用数组文字符号 []”。
I didn't find a reason to avoid using the constructor. Is in some way less efficient than using []
? Or is it bad practice?
我没有找到避免使用构造函数的理由。在某种程度上比使用效率低[]
吗?或者这是不好的做法?
Is there a good reason to use var arr = [];
instead of var arr = new Array();
?
有充分的理由使用var arr = [];
而不是var arr = new Array();
吗?
回答by Alnitak
Mostly, people use var a = []
because Douglas Crockford says so.
大多数情况下,人们使用var a = []
是因为Douglas Crockford 这么说。
His reasons include the non-intuitive and inconsistent behaviour of new Array()
:
他的原因包括以下不直观和不一致的行为new Array()
:
var a = new Array(5); // an array pre-sized to 5 elements long
var b = new Array(5, 10); // an array with two elements in it
Note that there's no way with new Array()
to create an array with just onepre-specified number element in it!
请注意,无法new Array()
创建一个只有一个预先指定的数字元素的数组!
Using []
is actually more efficient, and safer too! It's possible to overwrite the Array
constructor and make it do odd things, but you can't overwrite the behaviour of []
.
使用[]
其实更高效,也更安全!可以覆盖Array
构造函数并让它做一些奇怪的事情,但你不能覆盖[]
.
Personally, I always use the []
syntax, and similarly always use {}
syntax in place of new Object()
.
就个人而言,我总是使用[]
语法,同样总是使用{}
语法代替new Object()
.
回答by zzzzBov
One significant difference is that []
will alwaysinstantiate a new Array, whereas new Array
could be hiHymaned to create a different object.
一个显著不同的是,[]
将始终实例化一个新的磁盘阵列,而new Array
可以被劫持来创建不同的对象。
(function () {
"use strict";
var foo,
bar;
//don't do this, it's a bad idea
function Array() {
alert('foo');
}
foo = new Array();
bar = [];
}());?
In my example code, I've kept the Array
function hidden from the rest of the document scope, however it's more likely that if you ever run into this sort of issue that the code won't have been left in a nice closure, and will likely be difficult to locate.
在我的示例代码中,我已经将Array
函数从文档范围的其余部分隐藏起来,但是更有可能的是,如果您遇到此类问题,代码将不会留在一个很好的闭包中,并且会可能很难找到。
Disclaimer: It's not a good idea to hiHyman the Array
constructor.
免责声明:劫持Array
构造函数不是一个好主意。
回答by JL235
for maintainability, use []
为了可维护性,使用 []
The array literal is more predictable, as most developers use it. Most array usage out there will be using the literal, and there is value in having your code match up with what other developers use.
数组字面量更可预测,因为大多数开发人员都使用它。大多数数组用法都将使用文字,并且让您的代码与其他开发人员使用的代码相匹配是有价值的。
for empty arrays, use []
对于空数组,请使用 []
var ns = [];
var names = [ 'john', 'brian' ];
As shown here, using the literal for empty and a couple of known elements is fatster than the Array constructor.
如这里所示,使用空和几个已知元素的文字比 Array 构造函数更胖。
for an array of known size, use new Array(size)
对于已知大小的数组,请使用 new Array(size)
If the size is known, then using the Array constructor significantly improves performance. However it also means you have to deal with an array which already has 'undefined' filling all it's values.
如果大小已知,则使用 Array 构造函数可以显着提高性能。然而,这也意味着您必须处理一个已经填充了所有值的“未定义”数组。
As shown here
如图所示这里
// fill an array with 100 numbers
var ns = new Array( 100 );
for ( var i = 0; i < 100; i++ ) {
ns[i] = i;
}
This also works for very small arrays too.
这也适用于非常小的数组。
回答by jAndy
No, there is actually no reason to use one notation over the other one for empty Arrays.
不,实际上没有理由对空数组使用一种符号而不是另一种符号。
However, most browsers show a slightly better performance using x = [];
than calling the Constructor.
但是,大多数浏览器使用x = [];
比调用Constructor显示出稍好的性能。
If you need to create an Array with a specific size, you kind of needto use x = new Array(10);
for instance, which would create an Array with 10 undefined
slots.
如果您需要创建具有特定大小的 Array,您需要使用x = new Array(10);
例如,这将创建一个具有 10undefined
个插槽的 Array 。
回答by Yasir Mahmood
- var arr=[] uses the array/object literal
- var arr = new Array() use the array/object constructor
- var arr=[] 使用数组/对象字面量
- var arr = new Array() 使用数组/对象构造函数
The speediest way to define an array or object is literal way, because you don't need to call the constructor
定义数组或对象的最快方式是字面方式,因为您不需要调用构造函数
var arr1 = new Array(1, 2, 3, 4);
var arr2 = [1, 2, 3, 4];
alert(arr1[0]); // 1
alert(arr2[0]); // 1
var arr3 = new Array(200);
var arr4 = [200];
alert(arr3[0]); // 'undefined'
alert(arr4[0]); // 200
回答by RAN
Both are correct only. But most of the people use var a = []
只有两者都是正确的。但是大部分人都用var a = []
Three Ways to Declare an Array in JavaScript.
在 JavaScript 中声明数组的三种方法。
method 1: We can explicitly declare an array with the JavaScript "new" keyword to instantiate the array in memory (i.e. create it, and make it available).
方法 1:我们可以使用 JavaScript 的“new”关键字显式声明一个数组,以在内存中实例化该数组(即创建它并使其可用)。
// Declare an array (using the array constructor)
var arlene1 = new Array();
var arlene2 = new Array("First element", "Second", "Last");
method 2: we use an alternate method to declaring arrays.
方法 2:我们使用另一种方法来声明数组。
// Declare an array (using literal notation)
var arlene1 = [];
var arlene2 = ["First element", "Second", "Last"];
method 3: JavaScript also lets you create arrays indirectly, by calling specific methods.
方法 3:JavaScript 还允许您通过调用特定方法间接创建数组。
// Create an array from a method's return value
var carter = "I-learn-JavaScript";
var arlene3 = carter.split("-");
回答by linquize
var array = [ 1, 2, 3, 4];
is sugar
是糖
var array = new Array(1, 2, 3, 4);
is salt
是盐
回答by Erwin Moller
There is a limit the constructor can take as arguments.
构造函数可以作为参数有一个限制。
On most systems I encoutered the limit is 2^16 (2 bytes):
在我遇到的大多数系统上,限制是 2^16(2 个字节):
var myFreshArr = new Array(0,1,2,3 ..... 65536);
That will cause an error (too many arguments....)
这将导致错误(参数太多....)
When using the literal [] you don't have such problems.
使用文字 [] 时,您不会遇到此类问题。
In case you don't care about such big arrays, I think you can use whatever you prefer.
如果你不关心这么大的数组,我认为你可以使用任何你喜欢的。
回答by Florent
It's because new Array()
is ambiguous. These are the correct constructors:
那是因为new Array()
暧昧。这些是正确的构造函数:
// Using brackets
[element0, element1, ..., elementN]
// Using new AND a list of elements
new Array(element0, element1, ..., elementN)
// Using new AND an integer specifying the array length
new Array(arrayLength)