admin管理员组

文章数量:1391947

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

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

Share Improve this question asked Nov 4, 2011 at 17:17 abbasabbas 4323 gold badges10 silver badges22 bronze badges 2
  • 1 var myarr=[]; and myarr[id]=msg; – Birey Commented Nov 4, 2011 at 17:20
  • Thanks giys...it worked the braces with my arr was a typo – abbas Commented Nov 4, 2011 at 17:23
Add a ment  | 

5 Answers 5

Reset to default 7

The syntax is:

Declaring myarr:

myarr = {};

Adding an item:

myarr[id] = msg;

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;
}

I think you mean:

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

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;

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

http://jsfiddle/qRuWz/

本文标签: Javascript associative array problemsStack Overflow