JavaScript - short way of declaring an associative array

前端 未结 4 2006
醉话见心
醉话见心 2021-01-01 11:33

Is there a short way of declaring an associative array like in PHP?

$myArray = array(\'a\' => \'b\'); // PHP Way

In JavaScript I\'d do i

4条回答
  •  再見小時候
    2021-01-01 11:53

    JavaScript does not have associative arrays. In your example, you declare myArray as array but then you assign an object to it. So your code is not different from this:

    var myObject = {};
    myObject['a'] = 'b';
    

    Update: A little correction. Actually, the original code does not destroy the array. It just appends a regular property to it. That's possible because JavaScript arrays are a subset of JavaScript objects.

提交回复
热议问题