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
2
  • 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"); Commented Feb 15, 2014 at 14:57
  • And this answer explains it rather well: stackoverflow.com/a/2051893/921204 Commented Feb 15, 2014 at 14:59

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.