Skip to content Skip to sidebar Skip to footer

Push An Associative Item Into An Array In Javascript

How can I correct the following code? JSFiddle

Solution 1:

To make something like associative array in JavaScript you have to use objects. ​

var obj = {}; // {} will create an objectvar name = "name";
var val = 2;
obj[name] = val;
console.log(obj);

DEMO:http://jsfiddle.net/bz8pK/1/

Solution 2:

JavaScript doesn't have associate arrays. You need to use Objects instead:

var obj = {};
var name = "name";
varval = 2;
obj[name] = val;
console.log(obj);​

To get value you can use now different ways:

console.log(obj.name);​
console.log(obj[name]);​
console.log(obj["name"]);​

Solution 3:

JavaScript has associative arrays.

Here is a working snippet.

<scripttype="text/javascript">var myArray = [];
  myArray['thank'] = 'you';
  myArray['no'] = 'problem';
  console.log(myArray);
</script>

They are simply called objects.

Solution 4:

Another method for creating a JavaScript associative array

First create an array of objects,

var arr = {'name': []};

Next, push the value to the object.

varval = 2;
  arr['name'].push(val);

To read from it:

varval = arr.name[0];

Post a Comment for "Push An Associative Item Into An Array In Javascript"