Jump to content

Adding a new associative element to an array


wongadob

Recommended Posts

I am trying to add another element to an associative array, but cannot figure out the correct syntax.

var sendData = new Array();sendData= {body: message, replied_to_id: id};if (group != null){sendData+={group_id: group};} 

I am pretty sure that syntax is wrong, but I am also sure I have tried every combination I can think of. Sorry its a newbie question but That is me!

Link to comment
Share on other sites

sendData.group_id = group

By the way, that's not an array, it's an object. Your second line of code is making the new Array() line useless. There are no associative arrays in Javascript.

Link to comment
Share on other sites

You actually don't need the first line at all. The second line is just overwriting the new Object you created with another new Object, not adding properties to an existing Object. If you just want to add properties you use the syntax Ingolme showed.

Link to comment
Share on other sites

Also, there's really no reason to use the new keyword when literal syntax will work just as easy, and without the overhead of calling the constructor

myArray = []; //new Array()myObject = {}; //new Object()myString = "";  //new String("");myNum = 3; //new Number(3);myBool = true; //new Boolean;

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...