Jump to content

Javascript multi dimensionals array with keys


Drongo_III
 Share

Go to solution Solved by Drongo_III,

Recommended Posts

Hi Guys

 

Super simple question. I want to create a multidimensional JS array where I can define the keys. Perhaps my mistake is using similar syntax to php but the following code throws an error in chrome console saying "Uncaught TypeError: Cannot set property 'top' of undefined "

 

Can anyone nudge me in the right direction on this?

 

var locObj = [];
locObj[1]['top'] = 200;
alert(locObj[1]['top']);

 

 

Link to comment
Share on other sites

  • Solution

Worked it out now.

 

Seems you have to declare that the first array level is an array too:

 

var locObj = [];
locObj[1] = [];
locObj[1]['top'] = 'twinky'

alert(locObj[1]['top']);

 

 

Just thought I would post back in case anyone else gets stuck on something similar.

 

Though why you can't just write it like php is hard to fathom - still that's javascript for ya!

Link to comment
Share on other sites

There is a payoff - if you could do it like PHP (a 'loose' language), then it would require more overhead, slowing things down. By having to declare each element, there is less overhead, making for smoother running scripts.

Link to comment
Share on other sites

This thread is more than a year old.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

 Share

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.