What’s the difference between “Array()” and “[]” w

2018-12-31 02:26发布

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

var myArray = new Array();

and

var myArray = [];

15条回答
闭嘴吧你
2楼-- · 2018-12-31 02:52

I've incurred in a weird behaviour using [].

We have Model "classes" with fields initialised to some value. E.g.:

require([
  "dojo/_base/declare",
  "dijit/_WidgetBase",
], function(declare, parser, ready, _WidgetBase){

   declare("MyWidget", [_WidgetBase], {
     field1: [],
     field2: "",
     function1: function(),
     function2: function()
   });    
});

I found that when the fields are initialised with [] then it would be shared by all Model objects. Making changes to one affects all others.

This doesn't happen initialising them with new Array(). Same for the initialisation of Objects ({} vs new Object())

TBH I am not sure if its a problem with the framework we were using (Dojo)

查看更多
有味是清欢
3楼-- · 2018-12-31 02:54

I've found one difference between the two constructions that bit me pretty hard.

Let's say I have:

function MyClass(){
  this.property1=[];
  this.property2=new Array();
};
var MyObject1=new MyClass();
var MyObject2=new MyClass();

In real life, if I do this:

MyObject1.property1.push('a');
MyObject1.property2.push('b');
MyObject2.property1.push('c');
MyObject2.property2.push('d');

What I end up with is this:

MyObject1.property1=['a','c']
MyObject1.property2=['b']
MyObject2.property1=['a','c']
MyObject2.property2=['d']

I don't know what the language specification says is supposed to happen, but if I want my two objects to have unique property arrays in my objects, I have to use new Array().

查看更多
素衣白纱
4楼-- · 2018-12-31 02:58

There is no big difference, they basically do the same thing but doing them in different ways, but read on, look at this statement at W3C:

var cars = ["Saab", "Volvo","BMW"];

and

var cars = new Array("Saab", "Volvo", "BMW");

The two examples above do exactly the same. There is no need to use new Array().
For simplicity, readability and execution speed, use the first one (the array literal method).

But at the same time, creating new array using new Array syntax considered as a bad practice:

Avoid new Array()

There is no need to use the JavaScript's built-in array constructor new Array().
Use [] instead.
These two different statements both create a new empty array named points:

var points = new Array();         // Bad
var points = [];                  // Good 

These two different statements both create a new array containing 6 numbers:

var points = new Array(40, 100, 1, 5, 25, 10); // Bad    
var points = [40, 100, 1, 5, 25, 10];          // Good

The new keyword only complicates the code. It can also produce some unexpected results:

var points = new Array(40, 100);  // Creates an array with two elements (40 and 100)

What if I remove one of the elements?

var points = new Array(40);       // Creates an array with 40 undefined elements !!!!!

So basically not considered as the best practice, also there is one minor difference there, you can pass length to new Array(length) like this, which also not a recommended way.

查看更多
裙下三千臣
5楼-- · 2018-12-31 02:59

As I know the diference u can find the slice(or the other funcitons of Array) like code1.and code2 show u Array and his instances:

code1:

[].slice; // find slice here
var arr = new Array();
arr.slice // find slice here
Array.prototype.slice // find slice here

code2:

[].__proto__ == Array.prototype; // true
var arr = new Array();
arr.__proto__ == Array.prototype; // true

conclusion:

as u can see [] and new Array() create a new instance of Array.And they all get the prototype functions from Array.prototype

They are just different instance of Array.so this explain why [] != []

:)

查看更多
与君花间醉酒
6楼-- · 2018-12-31 03:01

There is a huge difference that no one mentioned.

You might think the new Array(2) is equivalent to [undefined, undefined] before because we have

new Array(2).length           // 2
new Array(2)[0] === undefined // true
new Array(2)[1] === undefined // true

BUT IT'S NOT!

Let's try map():

[undefined, undefined].map(e => 1)  // [1, 1]
new Array(2).map(e => 1)            // "(2) [undefined × 2]" in Chrome

See? It's different! But why is that?

According to ES6 Spec 22.1.1.2, Array(len) only creates a new array with length set to len and nothing more. Thus there is no real element inside the new array.

While function map(), according to spec 22.1.3.15 would firstly check HasProperty then call the callback, but it turns out that:

new Array(2).hasOwnProperty(0) // false
[undefined, undefined].hasOwnProperty(0) // true

That's why you can not expect any iteration functions work as usual to array created from new Array(len).

BTW, Safari and Firefox have a much better expression to this:

// Safari
new Array(2)             // [](2)
new Array(2).map(e => 1) // [](2) 
[undefined, undefined]   // [undefined, undefined] (2) 

// Firefox
new Array(2)             // Array [ <2 empty slots> ]
new Array(2).map(e => 1) // Array [ <2 empty slots> ]
[undefined, undefined]   // Array [ undefined, undefined ]

I have already submitted an issue to Chrome to ask them to fix this confusing log: https://bugs.chromium.org/p/chromium/issues/detail?id=732021

UPDATE: It's already fixed. Chrome now log as

new Array(2)             // (2) [empty × 2]
查看更多
姐姐魅力值爆表
7楼-- · 2018-12-31 03:01

Oddly enough, new Array(size) is almost 2x faster than [] in Chrome, and about the same in FF and IE (measured by creating and filling an array). It only matters if you know the approximate size of the array. If you add more items than the length you've given, the performance boost is lost.

查看更多
登录 后发表回答