JavaScript - short way of declaring an associative array

前端 未结 4 2015
醉话见心
醉话见心 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:58

    Declare an object like this:

    var myArray = {"a": "b", "c": "d"};
    

    ... and then refer to each item like this:

    var somethingElse = myArray["a"]; //Sets "somethingElse" to "b".
    

    As @Chris and @Marc mention in the comments: in JavaScript, objects ARE associative arrays, and vice versa, they just refer to two different ways of doing the same thing. For Example...

    var somethingElse = myArray["a"];
    var anotherVariable = myArray.a;
    

    ... do the same thing.

提交回复
热议问题