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

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

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

提交回复
热议问题