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

前端 未结 7 2009
盖世英雄少女心
盖世英雄少女心 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:27

    The difference between the arrays and the other objects in JavaScript. While arrays have a magically updating length property, for objects other than the arrays there is no way to implement such a property.

    var arrName = [];
    arrName[5] = "test";
    arrName.length; // <- 6
    

    Array are used to store things with an ordinal index - use it like a traditional array, stack, or queue. An object is a hash - use it for data that has a distinct key.

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