The thing to realize is that there are no multi-dimensional arrays in javascript. It is easy to make an array element contain an array, and work with that, but then all references you make have to use that consideration.
So, you can do
arr = []; // or more appropriately {}, but I'll get to that soon
arr['house'] = [];
arr['house']['rooms'] = 2;
But doing
arr['house']['rooms'] = 2;
should give you an error unless you've already defined arr
and arr['house']
.
If you've defined arr
but not arr['house']
, it's valid syntax to reference arr['house']
- but the return value will (appropriately) be undefined
.
And this is where you're at when you're looking at arr['plane']['room']
. arr
is defined, so that's ok, but arr['plane']
returns undefined, and referencing undefined.['room']
throws an error.
If you want to avoid the errors and have multiple levels of reference, you're going to have to make sure that all the levels but the lowest exist.
You're stuck with if (arr && arr['plane'] && arr['plane']['room'])
.
Or perhaps if (arr && arr['plane'] && room in arr['plane']
would be more accurate, depending on your needs. The first will check if arr['plane']['room']
has a truthy value, while the second will check if arr['plane']['room']
exists at all (and could have a falsey value).
Arrays vs objects
Arrays and objects are very similar and can both be accessed with []
notation, so it's slightly confusing, but technically, you're using the object aspect of the array for what you're doing. Remember, all arrays (and everything other than primitives - numbers, strings and booleans) are objects, so arrays can do everything objects can do, plus more. But arrays only work with numeric indices, i.e. arr[1][2]. When you reference an array with a string, you're attempting to access the member of the underlying object that matches that string.
But still in this case, it doesn't matter. There are no multi-dimensional arrays - or objects.
The []
notation with objects is simply a way to check for members of objects using a variable. arr['plane']['rooms'] is actually equivalent to arr.plane.rooms
. but perhaps the arr.plane.room
notation will help make it more clear why you have to first check arr.plane
(and arr
).