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

后端 未结 18 1372
生来不讨喜
生来不讨喜 2020-11-21 12:00

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

var myArray = new Array();

and

var myArray = [];
<         


        
相关标签:
18条回答
  • 2020-11-21 12:34

    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.
    
    0 讨论(0)
  • 2020-11-21 12:35

    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)

    0 讨论(0)
  • 2020-11-21 12:39

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

    :)

    0 讨论(0)
  • 2020-11-21 12:41

    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.

    0 讨论(0)
  • 2020-11-21 12:43

    Well, var x = new Array() is different than var x = [] is different in some features I'll just explain the most useful two (in my opinion) of them.

    Before I get into expalining the differences, I will set a base first; when we use x = [] defines a new variable with data type of Array, and it inherits all the methods that belong to the array prototype, something pretty similar (but not exactly) to extending a class. However, when we use x = new Array() it initilizes a clone of the array prototype assigned to the variable x.

    Now let's see what are the difference

    The First Difference is that using new Array(x) where x is an integer, initilizes an array of x undefined values, for example new Array(16) will initialize an array with 16 items all of them are undefined. This is very useful when you asynchronously fill an array of a predefined length. For example (again :) ) let's say you are getting the results of 100 competitiors, and you're receiving them asynchronously from a remote system or db, then you'll need to allocate them in the array according to the rank once you receive each result. In this very rare case you will do something like myArray[result.rank - 1] = result.name, so the rank 1 will be set to the index 0 and so on.

    The second difference is that using new Array() as you already know, instanciates a whole new clone of the array prototype and assigns it to your variable, that allows you to do some magic (not recommended btw). This magic is that you can overwrite a specific method of the legacy array methods. So, for example you can set the Array.push method to push the new value to the beginning of the array instead of the end, and you can also add new methods (this is better) to this specific clone of the Array Prototype. That will allow you to define more complex types of arrays throughout your project with your own added methods and use it as a class.

    Last thing, if you're from the very few people (that I truly love) that care about processing overhead and memory consumption of your app, you'd never tough new Array() without being desperate to use it :).

    I hope that has explained enough about the beast new Array() :)

    0 讨论(0)
  • 2020-11-21 12:46

    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.

    0 讨论(0)
提交回复
热议问题