简体   繁体   中英

Define associative array of arrays

I want to define an associative array like this

var theVar = [
  { "100", [0, 1, 2] },
  { "101", [3, 4, 5] }
]

Essentially I want to be able to access an array of three numbers by specifying the custom index.

However, no matter what I try I cannot make it work.

I know I can define it as:

theVar["100"] = [0, 1, 2];
theVar["101"] = [1, 2, 3];

But I am setting this somewhere else and I'd prefer to be able to set it in a single statement.

theVar = {
  "100": [0, 1, 2],
  "101": [3, 4, 5]
}

might do the trick. You can then access using theVar["101"] (or theVar[101] for that matter).

(As var is also a keyword in JavaScript, using it as a variable name is very likely to cause problems.)

Have a look at the JSON syntax, I think It could inspire the building of your data structures in a way that will be flexible, correct and complex as you want.

This page has a lot of information and example that are helpful for you.

For instance look at this:

var employees = { "accounting" : [   // accounting is an array in employees.
                                    { "firstName" : "John",  // First element
                                      "lastName"  : "Doe",
                                      "age"       : 23 },

                                    { "firstName" : "Mary",  // Second Element
                                      "lastName"  : "Smith",
                                      "age"       : 32 }
                                  ], // End "accounting" array.                                  
                  "sales"       : [ // Sales is another array in employees.
                                    { "firstName" : "Sally", // First Element
                                      "lastName"  : "Green",
                                      "age"       : 27 },

                                    { "firstName" : "Jim",   // Second Element
                                      "lastName"  : "Galley",
                                      "age"       : 41 }
                                  ] // End "sales" Array.
                } // End Employees

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