user1845742
user1845742

Reputation: 21

How do I get a value in an array within an array

I got a structure like this:

var Array = new Array(3);

Array["123"] = ["a","b","c"];

Array["456"] = ["d","e","f"];

Array["789"] = ["g","h","i"];

for example, how do I get "b"

Upvotes: 1

Views: 151

Answers (4)

user1726343
user1726343

Reputation:

Array is a native constructor. Using a new object that doesn't add properties to the native object:

var obj = {};

obj["123"] = ["a","b","c"];

obj["456"] = ["d","e","f"];

obj["789"] = ["g","h","i"];

obj["123"][1]; // "123"

What your code was doing was adding a bunch of properties to the native Array, (which is a function object that makes array objects). For more on the difference between arrays and other objects, see this question

Upvotes: 0

agent-j
agent-j

Reputation: 27913

a["123"][1]; // yields "b"
a[123][1]; // also yields "b"

Indexing an array with a string is probably not what you meant to do.

var a = new Array(3);

a["123"] = ["a","b","c"];  // "123" causes the array to expand to [0..123]
a["123"][1]; // yields "b"
a[123] = ["a","b","c"];  // this has better performance and is idiomatic javascript.
a[123][1]; // also yields "b"
a["456"] = ["d","e","f"];
a["789"] = ["g","h","i"];

If you want to use an object as a map instead, try this:

a = new object()
a["123"] = ["a","b","c"];
a["123"][1]; // yields "b"

Upvotes: 1

Boris Gappov
Boris Gappov

Reputation: 2493

var a = new Array();   
a["123"] = ["a","b","c"];
a["456"] = ["d","e","f"];
a["789"] = ["g","h","i"];
b = a["123"][1];

sample :) http://jsbin.com/agolef/1/edit

Upvotes: 1

DarkAjax
DarkAjax

Reputation: 16223

Use something like this (you don't need the quotes):

array[123][1]

Upvotes: 0

Related Questions