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,713
  • 2
  • 14
  • 16

3 Answers3

2

messages[userId] does not exist.

You need to put an array there:

messages[userId] = [];
SLaks
  • 837,282
  • 173
  • 1,862
  • 1,933
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
  • 70,503
  • 15
  • 107
  • 148
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