Drongo_III Posted March 27, 2013 Share Posted March 27, 2013 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']); Quote Link to comment https://forums.phpfreaks.com/topic/276219-javascript-multi-dimensionals-array-with-keys/ Share on other sites More sharing options...
Solution Drongo_III Posted March 27, 2013 Author Solution Share Posted March 27, 2013 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! Quote Link to comment https://forums.phpfreaks.com/topic/276219-javascript-multi-dimensionals-array-with-keys/#findComment-1421397 Share on other sites More sharing options...
haku Posted March 29, 2013 Share Posted March 29, 2013 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. Quote Link to comment https://forums.phpfreaks.com/topic/276219-javascript-multi-dimensionals-array-with-keys/#findComment-1421778 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.