user3313613
user3313613

Reputation: 1

saving values in two dimensional array javascript

I have seen other questions and all examples are like below

var arr = [1, 2, [3, 4], 5];

alert (arr[2][1]);

But i want somethingl ike this

var mmo = [];

mmo["name"] = "steve";
mmo["name"]["x"] = "20";
mmo["name"]["y"] = "40";

alert(mmo["name"]["y"]); // should alert 40 but its undefined

Upvotes: 0

Views: 355

Answers (1)

Guffa
Guffa

Reputation: 700382

You can't have both a value and an array in the same item.

Use an object instead of an array, as you want to use named propertes insted of numeric indices.

Put an object as the property, then you can put properties in that object:

var mmo = {};

mmo["name"] = {};
mmo["name"]["x"] = "20";
mmo["name"]["y"] = "40";

If you want to use an array in the object, then you would use numeric indices:

var mmo = {};

mmo["name"] = [];
mmo["name"][0] = "20";
mmo["name"][1] = "40";

If you want to use an array in an array, then it would all be numeric indices:

var mmo = [];

mmo[0] = [];
mmo[0][0] = "20";
mmo[0][1] = "40";

An array is also an object, so you could use an array and put properties in it, but that is mostly confusing.

Upvotes: 2

Related Questions