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

4
  • Exists here: stackoverflow.com/a/1590262/1519323 Commented Oct 19, 2012 at 15:53
  • {} is an objecct, [] is an array Commented Oct 19, 2012 at 15:54
  • @laser_wizard: that's not quite what I want to do. I want to then be able to access the message list of a particular userId Commented Oct 19, 2012 at 15:56
  • @Diodeus: I know, I'm just getting crazy litterally! trying to get assoc arrays working for me has always been a pain and this evening I really am offline! Commented Oct 19, 2012 at 15:57

3 Answers 3

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"); 
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you. This works. What about getting a particular userId's message queue?
@johnsmith: messages[userId]
The userId is a property of the messages object, you can just do messages[userId], or messages[123].
2

messages[userId] does not exist.

You need to put an array there:

messages[userId] = [];

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.