Consider this example Javascript code:
a = new Array();
a['a1']='foo';
a['a2']='bar';
b = new Array(2);
b['b1']='foo';
b['b2']='bar';
c=['c1','c2','c3'];
console.log(a);
console.log(b);
console.log(c);
Results in the Firebug console are as follows:
For a (the '[]' had to be expanded by clicking on the '+' button):
[]
a1 "foo"
a2 "bar"
For b:
[undefined, undefined]
For c:
["c1", "c2", "c3"]
My questions are:
- Am I using the array['key']='value' syntax correctly?
- Why isn't array b working as expected?
- Why are arrays a and c displayed differently in the console? It also seems that jQuery is unable to iterate through the array a with it's .each() method.
- Could you reccomend any good tutorials on Javascript array behaviour?
NOTE: Google Chrome's Firebug displays only [] for array 'a', without the option to expand it.
EDIT: Alright, it seems that arrays in Javascript have only numerical keys, so adding a string as a key name makes an object out of an array. But why doesn't jQuery's .each work with it?
$.each(a, function ()
{
alert ('derp');
})
This code, appended to the script, produces no alerts.
a['a1'] = valadds a propertya1to the objecta, not an array value.