How to create an associative array in JavaScript literal notation

前端 未结 6 710
再見小時候
再見小時候 2021-01-30 16:39

I understand that there are no associative arrays in JavaScript, only objects.

However I can create an array with string keys using bracket

6条回答
  •  遇见更好的自我
    2021-01-30 17:36

    Well, you are creating an array, which is in fact an object:

    var arr = [];
    arr.map;
    // function(..)
    arr['map'];
    // function(..)
    
    arr['a'] = 5;
    
    console.log(arr instanceof Object); // true
    

    You can add fields and functions to arr. It does not "insert" them into the array though (like arr.push(...)).

    You can refer to an object fields with the [] syntax.

提交回复
热议问题