admin管理员组

文章数量:1130762

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 []."

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();?

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 []."

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();?

Share Improve this question edited Jul 16, 2012 at 12:17 Bill the Lizard 405k211 gold badges572 silver badges889 bronze badges asked Jul 16, 2012 at 8:21 NaigelNaigel 9,64417 gold badges71 silver badges109 bronze badges 5
  • 5 Both are fine. You just save some bytes in transmission. – Sirko Commented Jul 16, 2012 at 8:22
  • 14 There are indeed differences. See this post: stackoverflow.com/q/2280285/921204 – techfoobar Commented Jul 16, 2012 at 8:25
  • Note: there are differences if Array has been overwritten only. – crdx Commented Jul 18, 2012 at 12:19
  • @apkd on some browsers there's a significant performance difference – Alnitak Commented Jul 18, 2012 at 17:36
  • Fair enough. I didn't see that on the linked question. – crdx Commented Jul 19, 2012 at 7:18
Add a comment  | 

9 Answers 9

Reset to default 265

Mostly, people use var a = [] because Douglas Crockford says so.

His reasons include the non-intuitive and inconsistent behaviour of 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!

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 [].

Personally, I always use the [] syntax, and similarly always use {} syntax in place of new Object().

One significant difference is that [] will always instantiate a new Array, whereas new Array could be hijacked to create a different object.

(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.

Disclaimer: It's not a good idea to hijack the Array constructor.

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.

for an array of known size, use 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.

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 = []; 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); for instance, which would create an Array with 10 undefined slots.

  • var arr=[] uses the array/object literal
  • var arr = new Array() use the array/object constructor

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 = []

Three Ways to Declare an Array in 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).

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

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

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

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

本文标签: What are the best practices to follow when declaring an array in Javascript Stack Overflow