Blog coding and discussion of coding about JavaScript, PHP, CGI, general web building etc.

Friday, December 25, 2015

What’s the difference between

What?s the difference between "Array()" and "[]" while declaring a JavaScript array?


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

var myArray = new Array();  

and

var myArray = [];  

Answer by nickf for What?s the difference between "Array()" and "[]" while declaring a JavaScript array?


There is a difference, but there is no difference in that example.

Using the more verbose method: new Array() does have one extra option in the parameters: if you pass a number to the constructor, you will get an array of that length:

x = new Array(5);  alert(x.length); // 5  

To illustrate the different ways to create an array:

var a = [],            // these are the same      b = new Array(),   // a and b are arrays with length 0        c = ['foo', 'bar'],           // these are the same      d = new Array('foo', 'bar'),  // c and d are arrays with 2 strings        // these are different:      e = [3]             // e.length == 1, e[0] == 3      f = new Array(3),   // f.length == 3, f[0] == undefined    ;  

Answer by Fredrik Mörk for What?s the difference between "Array()" and "[]" while declaring a JavaScript array?


Here is a piece of JavaScript code that will verify that both declarations lead to the same type:

var test1 = [];  test1.push("value");    var test2 = new Array();  test2.push("value");    alert(typeof(test1) == typeof(test2));  

Answer by Bogdan Gusiev for What?s the difference between "Array()" and "[]" while declaring a JavaScript array?


The first one is the default object constructor call. You can use it's parameters if you want.

var array = new Array(5); //initialize with default length 5  

The second one gives you the ability to create not empty array:

var array = [1, 2, 3]; // this array will contain numbers 1, 2, 3.  

Answer by BarelyFitz for What?s the difference between "Array()" and "[]" while declaring a JavaScript array?


For more information, the following page describes why you never need to use new Array():

http://yuiblog.com/blog/2006/11/13/javascript-we-hardly-new-ya/

You never need to use new Object() in JavaScript. Use the object literal {} instead. Similarly, don?t use new Array(), use the array literal [] instead. Arrays in JavaScript work nothing like the arrays in Java, and use of the Java-like syntax will confuse you.

Do not use new Number, new String, or new Boolean. These forms produce unnecessary object wrappers. Just use simple literals instead.

Also check out the comments - the new Array(length) form does not serve any useful purpose (at least in today's implementations of JavaScript).

Answer by coderjoe for What?s the difference between "Array()" and "[]" while declaring a JavaScript array?


The difference between creating an array with the implicit array and the array constructor is subtle but important.

When you create an array using

var a = [];  

You're telling the interpreter to create a new runtime array. No extra processing necessary at all. Done.

If you use:

var a = new Array();  

You're telling the interpreter, I want to call the constructor "Array" and generate an object. It then looks up through your execution context to find the constructor to call, and calls it, creating your array.

You may think "Well, this doesn't matter at all. They're the same!". Unfortunately you can't guarantee that.

Take the following example:

function Array() {      this.is = 'SPARTA';  }    var a = new Array();  var b = [];    alert(a.is);  // => 'SPARTA'  alert(b.is);  // => undefined  a.push('Woa'); // => TypeError: a.push is not a function  b.push('Woa'); // => 1 (OK)  

In the above example, the first call will alert 'SPARTA' as you'd expect. The second will not. You will end up seeing undefined. You'll also note that b contains all of the native Array object functions such as push, where the other does not.

While you may expect this to happen, it just illustrates the fact that [] is not the same as new Array().

It's probably best to just use [] if you know you just want an array. I also do not suggest going around and redefining Array...

Cheers!

Answer by galambalazs for What?s the difference between "Array()" and "[]" while declaring a JavaScript array?


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.

Answer by Peter Lee for What?s the difference between "Array()" and "[]" while declaring a JavaScript array?


In order to better understand [] and new Array():

> []    []  > new Array()    []  > [] == []    false  > [] === []    false  > new Array() == new Array()    false  > new Array() === new Array()    false  > typeof ([])    "object"  > typeof (new Array())    "object"  > [] === new Array()    false  > [] == new Array()    false  

The above result is from Google Chrome console on Windows 7.

Answer by Kholio for What?s the difference between "Array()" and "[]" while declaring a JavaScript array?


I can explain in a more specific way starting with this example that's based on Fredrik's good one.

var test1 = [];  test1.push("value");  test1.push("value2");    var test2 = new Array();  test2.push("value");  test2.push("value2");    alert(test1);  alert(test2);  alert(test1 == test2);  alert(test1.value == test2.value);  

I just added another value to the arrays, and made four alerts: The first and second are to give us the value stored in each array, to be sure about the values. They will return the same! Now try the third one, it returns false, that's because

JS treats test1 as a VARIABLE with a data type of array, and it treats test2 as an OBJECT with the functionality of an array, and there are few slight differences here.

The first difference is when we call test1 it calls a variable without thinking, it just returns the values that are stored in this variable disregarding its data type! But, when we call test2 it calls the Array() function and then it stores our "Pushed" values in its "Value" property, and the same happens when we alert test2, it returns the "Value" property of the array object.

So when we check if test1 equals test2 of course they will never return true, one is a function and the other is a variable (with a type of array), even if they have the same value!

To be sure about that, try the 4th alert, with the .value added to it; it will return true. In this case we tell JS "Disregarding the type of the container, whether was it function or variable, please compare the values that are stored in each container and tell us what you've seen!" that's exactly what happens.

I hope I said the idea behind that clearly, and sorry for my bad English.

Answer by Bucky for What?s the difference between "Array()" and "[]" while declaring a JavaScript array?


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

Answer by Timothy Trousdale for What?s the difference between "Array()" and "[]" while declaring a JavaScript array?


Using the Array constructor makes a new array of the desired length and populates each of the indices with undefined, the assigned an array to a variable one creates the indices that you give it info for.


Fatal error: Call to a member function getElementsByTagName() on a non-object in D:\XAMPP INSTALLASTION\xampp\htdocs\endunpratama9i\www-stackoverflow-info-proses.php on line 72

0 comments:

Post a Comment

Popular Posts

Powered by Blogger.