Why can I add named properties to an array as if it were an object?

前端 未结 7 2007
盖世英雄少女心
盖世英雄少女心 2020-11-22 06:33

The following two different code snippets seem equivalent to me:

var myArray = Array();
myArray[\'A\'] = \"Athens\";
myArray[\'B\'] = \"Berlin\";
         


        
7条回答
  •  囚心锁ツ
    2020-11-22 07:09

    Everything in JavaScript is an object besides primitive types.

    The code

    var myArray = Array();
    

    creates an instance of the Array object while

    var myObject = {'A': 'Athens', 'B':'Berlin'};
    

    creates an instance of Object object.

    Try the following code

    alert(myArray.constructor)
    alert(myObject.constructor)
    

    So you will see the difference is in the type of object constructor.

    The instance of the Array object will contain all the properties and methods of the Array prototype.

提交回复
热议问题