JavaScript - short way of declaring an associative array

前端 未结 4 2001
醉话见心
醉话见心 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 12:00

    In javascript, associative arrays, keyed collections, hashes, ... whatever you want to call them, are not a special type. All the following are good.

    a = {}
    a[3] = 15
    a.b = "c"
    a['def'] = 'something'
    

    This code produces a single valid object with the properties you would expect. All of them. You can combine a conventionally indexed array and an associative array in one object.

    As to declaring a whole bunch at once, the usual syntax is:

    a = {
        'key1' : 'val1',
        'key2' : val2,
        key3 : val3,
        key4 : "val4"
    }
    

提交回复
热议问题