简体   繁体   English

在Javascript中声明数组时要遵循的最佳做法是什么?

[英]What are the best practices to follow when declaring an array in Javascript?

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 = []; 是否有充分的理由使用var arr = []; instead of var arr = new Array(); 而不是var arr = new Array(); ?

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 one pre-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()

One significant difference is that [] will always instantiate a new Array, whereas new Array could be hijacked 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 hijack the Array constructor. 免责声明 :劫持Array构造函数不是一个好主意。

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构造fatster。

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. 如果已知大小,则使用Array构造函数可显着提高性能。 However it also means you have to deal with an array which already has 'undefined' filling all it's values. 然而,这也意味着你必须处理一个已经有'undefined'填充所有值的数组。

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 . 这也适用于非常小的阵列

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 = []; 但是,大多数浏览器使用x = [];显示稍好的性能x = []; than calling the Constructor . 而不是调用构造函数

If you need to create an Array with a specific size, you kind of need to use x = new Array(10); 如果需要创建具有特定大小的数组,则需要使用x = new Array(10); for instance, which would create an Array with 10 undefined slots. 例如,它将创建一个包含10个undefined插槽的Array。

  • var arr=[] uses the array/object literal var arr = []使用数组/对象文字
  • var arr = new Array() use the array/object constructor 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

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 (ie 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("-");

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. 如果你不关心这样的大阵列,我认为你可以使用你喜欢的任何东西。

var array = [ 1, 2, 3, 4];

is sugar 是糖

var array = new Array(1, 2, 3, 4);

is salt 是盐

It's because new Array() is ambiguous. 这是因为new Array()含糊不清。 These are the correct constructors: 这些是正确的构造函数:

// 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)

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

相关问题 在使用JavaScript构建HTML时,保持关注点分离的最佳做法是什么? - What are best practices to maintain separation of concerns when building HTML with JavaScript? JavaScript中声明数组的方式是什么? - What is the way of declaring an array in JavaScript? 在JavaScript中使用一些empy元素声明数组时发生了什么 - What's happening when declaring array with a few empy elements in JavaScript 声明或分配类型的最佳实践 - Best practices for declaring or assigning types 编写和组织javascript插件的最佳做法是什么? - What are the best practices for writing and organizing javascript plugins? JavaScript 错误处理的最佳实践是什么? - What are the best practices for JavaScript error handling? 防止陈旧 CSS 和 JavaScript 的最佳做法是什么 - What are best practices for preventing stale CSS and JavaScript 定义JavaScript变量的最佳做法 - Best practices when defining JavaScript variables 对象数组,在寻找最大值时使我的代码可读的最佳实践是什么 - object array, what are the best practices to make my code readable when I'm looking for a maximum value 在实施聊天服务时我应该遵循哪些最佳实践和标准? - what are best practices and standards I should follow while implementing a chat service?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM