Reputation: 432
i have a function
var myarr[] =new Object();
function myfunction(id,msg)
{
myarr[id,msg]
}
I am trying to add msg with id as a key...but its not working...plz help
Upvotes: 0
Views: 991
Reputation: 6955
You are misunderstanding how to create associative arrays. Herei s a jsfiddle with the correct functionality.
Upvotes: 0
Reputation: 47988
First, you don't included the brackets []
when declaring a variable as an Array or Object in JavaScript.
var myarr = new Object();
Secondly, you need to adjust your assignments:
myarr[id] = msg;
Upvotes: 0
Reputation: 8471
The syntax is:
Declaring myarr:
myarr = {};
Adding an item:
myarr[id] = msg;
Upvotes: 7
Reputation: 349002
JavaScript is not Java.
The following function will create an array consisting of objects.
var myarr = []; //Or: var myarr = {};
function myfunction(id, msg) {
var obj = {}; //Create object
obj[id] = msg; //Set property with key=id, with value=msg
myarr.push(obj); //Use `push` method of the array to insert object in an array
}
If you want to create a single object, and set properies using key=id, and value=msg, use:
var myarr = {};
function myfunction(id, msg){
myarr[id] = msg;
}
Upvotes: 3