简体   繁体   中英

Creating Javascript multidimensional associative array

Here is how a multidimensional associative array (I mean object, as multidimensional associative array is not present in JavaScript) is defined generally in JavaScript,

var array = {};
array['fruit'] = {};
array['fruit']['citrus'] = ['lemon', 'orange'];

In other languages like PHP, it can be defined as,

$array['fruit']['citrus'] = ['lemon', 'orange'];

Is it possible to create a multidimensional associative array in JavaScript like this?

var array = {
    fruit: {
        citrus: ['Lemon', 'Orange']
    }
};

var fruits = array["fruit"];
>>> {"citrus": ["Lemon", "Orange"]}

var citrus_fruits = fruits["citrus"];
>>> ["Lemon", "Orange"]

var orange = citrus_fruits[1];
>>> "Orange"

Also have a look at JSON - JavaScript Object Notation.

Sure, you can define it in one go like this:

var array = {
    fruit: {
       citrus: ['Lemon', 'Orange']
    }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM