I want to create an array of hashes in javascript. In other words, I want to do the following thing
var messages = new Array;
messages['info'].push(["info message1", "info message2", "info message3"]);
messages['error'].push(["error message1", "error message2", "error message3"]);
and then iterate through each key. But it gives me an error "Cannot call method 'push' of undefined"
How can I do it?
You are trying to access the property
infoofmessages, which does not exists, hence its value isundefined. You are then trying to treat it as an array by calling.push. That won’t work.I think what you actually want is to assign the arrays to each of those properties:
Only use arrays with numeric keys. Use plain objects for string keys.
Now that
messages.infois defined and as in array, you can add new messages to it:Learn more about objects.