1

I am using javascript to create a message queue, say for example I want to store the messages "hello" and "word" to user with id "123", I am using the following to set and retrieve them.

var messages = [];
var userId = 123;

messages[userId].push("hello");
messages[userId].push("word");

needless to say, this is not working, damn arrays! How can I make this work, keeping it as simple as possible?

Thanks in advance

john smith
  • 1,963
  • 2
  • 17
  • 16

3 Answers3

2

messages[userId] does not exist.

You need to put an array there:

messages[userId] = [];
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
2

You need an array ([]) for every user:

var messages = {};
var userId = 123; 
messages[userId] = ["hello", "word"];

You can use push too:

var messages = {};
var userId = 123; 
messages[userId] = [];
messages[userId].push("hello");
messages[userId].push("word"); 
bfavaretto
  • 71,580
  • 16
  • 111
  • 150
0

well, technically you could push elements as properties of an object, which you have created and then iterate thorugh its properties.

SzymonK
  • 98
  • 4