abbas
abbas

Reputation: 432

Javascript associative array problems

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

Answers (5)

Keith.Abramo
Keith.Abramo

Reputation: 6955

You are misunderstanding how to create associative arrays. Herei s a jsfiddle with the correct functionality.

http://jsfiddle.net/qRuWz/

Upvotes: 0

g.d.d.c
g.d.d.c

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

AlG
AlG

Reputation: 15157

I think you mean:

function myfunction(id,msg)
 {
    myarr[id] = msg;
 }

Upvotes: 3

Moishe Lettvin
Moishe Lettvin

Reputation: 8471

The syntax is:

Declaring myarr:

myarr = {};

Adding an item:

myarr[id] = msg;

Upvotes: 7

Rob W
Rob W

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

Related Questions