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

后端 未结 18 1465
生来不讨喜
生来不讨喜 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: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)

提交回复
热议问题