0

I'm trying to use an associative multi-dimensional array in javascript, but there is something wrong in the code.

html

<p onclick="myFunction()">Test</p>

javascript

myFunction = function() {

  alert(1);

  obj['temp']['room'] = 1;

  alert(2);

}

The result is that only the first alert is fired. What is wrong in the definition of the array?

sthor69
  • 638
  • 1
  • 10
  • 25
  • Given that there are no associative arrays in JavaScript, there aren't any multidimensional ones either. You can nest objects, though. – Bergi Oct 13 '16 at 17:20
  • 4
    Please learn [how to open the console in your browser](http://webmasters.stackexchange.com/q/8525), and read what it says. It likely says something is undefined. In this case, `obj`. – Heretic Monkey Oct 13 '16 at 17:20
  • 1
    See [How to open the JavaScript console in different browsers](http://webmasters.stackexchange.com/q/8525) and you'll find the error. – Bergi Oct 13 '16 at 17:21
  • Possible duplicate of [JavaScript multidimensional array](http://stackoverflow.com/questions/7545641/javascript-multidimensional-array) – Dez Oct 13 '16 at 17:23
  • -1 on my own question! :-( As you suggested, a simple console would have solved the problem – sthor69 Oct 13 '16 at 18:02

2 Answers2

2

You need to declare the variable and initialize it as object, then you can assign a value.

var obj = { temp: {} };
obj['temp']['room'] = 1;
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

That term "associative array" is just an alias for an object treated in a way that "associates" to how arrays are used in code (like in your example). Your code expects this (so, make sure you have it before attempting to use it):

var obj = {
  temp = {
    room = 1
  }
};
Hari Lubovac
  • 622
  • 4
  • 14