0

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

2
  • 1
    var myarr=[]; and myarr[id]=msg; Commented Nov 4, 2011 at 17:20
  • Thanks giys...it worked the braces with my arr was a typo Commented Nov 4, 2011 at 17:23

5 Answers 5

7

The syntax is:

Declaring myarr:

myarr = {};

Adding an item:

myarr[id] = msg;
Sign up to request clarification or add additional context in comments.

2 Comments

Can you tell me how to sort it as well...based on the id which is a string and not an int??
@abbas: You cannot sort object properties, they are unordered. I suggest you read the MDN JavaScript Guide and make yourself familiar with the difference between arrays and objects.
3

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

Comments

3

I think you mean:

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

Comments

0

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;

Comments

0

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

http://jsfiddle.net/qRuWz/

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.