Push an associative item into an array in JavaScript
How can I correct the following code?
var arr = [];
var name = "name";
var val = 2;
arr.push(val); //works , but not associative
arr[name] = val; //does not work
console.log(arr);
JSFiddle
Solution 1:
To make something like associative array in JavaScript you have to use objects.
var obj = {}; // {} will create an object
var 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";
var val = 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.
<script type="text/javascript">
var myArray = [];
myArray['thank'] = 'you';
myArray['no'] = 'problem';
console.log(myArray);
</script>
They are simply called objects.