0

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
  • Not sure why you'd want to have additional properties on a string. However, you can do the above, if you create it like `mmo["name"] = new String("steve");` – techfoobar Feb 15 '14 at 14:57
  • And this answer explains it rather well: http://stackoverflow.com/a/2051893/921204 – techfoobar Feb 15 '14 at 14:59

1 Answers1

2

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.

Guffa
  • 687,336
  • 108
  • 737
  • 1,005