var arr = {};
arr['foo'] = 'bar';
alert(arr.foo); // alerts 'bar'
We can also create this kind of arrays in a dynamic way, like so:
var arr = {};
var items = ['foo,bar', 'boo,baz'];
for(var i=0; i<items.length; i++) {
var item = items[i];
var values = item.split(',');
arr[values[0]] = values[1];
}
alert(arr.foo);
alert(arr.boo);
jQuery uses this kind of array-like objects for some of its Ajax methods (such as $.post()). We can actually retrieve the names and values of form elements and turn them in an associative array. Example:
var values = {};
$('#form :input').not(':submit').each(function() {
var $input = $(this);
var name = $input.attr('name');
var value = $input.val();
values[name] = value;
});
Now we can use $.post():
$.post('process.php', values, function(response, content){
// do something here
});
As you can see, retrieving this kind of values is pretty straightforward.
JavaScript has no native notion of associative arrays. Unlike PHP, JavaScript uses object literals to mimic the basic behavior of associative arrays. For example: