In a program i am writing i need an object variable that looks like this:
var map {
cube: {__pt3arraylocation__:[0,0,0], poly: new Object()},
other: {__pt3arraylocation__:[1,0,0], poly: new Object()}
};
However, i want to be able to type map.cube and have it return the pt3arraylocation as a default unless i specify what i want by typing map.cube.poly
for example: map.cube would return [0,0,0] and map.cube.poly would return the object poly in the object cube
thanks in advance
You can’t do that in JavaScript.
However, as an alternative, it’s worth noting that you can add arbitrary properties to arrays if you want to. So for instance:
Then
map.cubegives you the array, andmap.cube.polygives you the object you’ve stored on that array.How is this possible? Because in JavaScript, arrays aren’t really arrays. They’re just objects that have an automatic
lengthproperty, treat a class of property names (all numeric ones) in a special way, and haveArray.prototypebacking them up. And of course, you can add properties to any object.There’s no literal syntax for doing this, which is why I had to do it with assignments after the object initializer above. But it’s perfectly valid. I use it for cross-indexing arrays all the time.
Do be sure, if you do this, that you’re not using
for..inincorrectly; more.