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

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

    Virtually everything in javascript is an object, so you can "abuse" an Array object by setting arbitrary properties on it. This should be considered harmful though. Arrays are for numerically indexed data - for non-numeric keys, use an Object.

    Here's a more concrete example why non-numeric keys don't "fit" an Array:

    var myArray = Array();
    myArray['A'] = "Athens";
    myArray['B'] = "Berlin";
    
    alert(myArray.length);
    

    This won't display '2', but '0' - effectively, no elements have been added to the array, just some new properties added to the array object.

提交回复
热议问题