Is console.log() supposed to print out the value of a variable at the time it's called in your JavaScript? That was my assumption but when I run the code below in either Firefox (using Firebug) or Google Chrome (and use the built-in dev tools), I seem to get the "final" value of an array rather than the value of the array at that time. If I use alert() statements they print out what I would expect - the value of an array at the time the alert() statement is called.
var params = new Array();
var tmp = new Array('apple', 'banana', 'cat');
for (var i=0; i < tmp.length; i++) {
params[tmp[i]] = [];
}
console.log(params);
/*
SHOWS IN CONSOLE:
- []
+ apple ["jan", "feb", "mar", "apr"]
+ banana ["jan", "feb", "mar", "apr"]
+ apple ["jan", "feb", "mar", "apr"]
*/
alert( print_arr(params) );
/*
ALERT BOX TEXT:
[apple]:
[banana]:
[cat]:
*/
console.log('===========================================');
var tmp2 = new Array('jan', 'feb', 'mar', 'apr');
for (var i=0; i < tmp.length; i++) {
for (var j=0; j < tmp2.length; j++) {
params[tmp[i]].push(tmp2[j]);
}
}
console.log(params);
/*
SHOWS IN CONSOLE:
- []
+ apple ["jan", "feb", "mar", "apr"]
+ banana ["jan", "feb", "mar", "apr"]
+ apple ["jan", "feb", "mar", "apr"]
*/
alert( print_arr(params) );
/*
ALERT BOX TEXT:
[apple]:jan,feb,mar,apr
[banana]:jan,feb,mar,apr
[cat]:jan,feb,mar,apr
*/
function print_arr(arr) {
var str = '';
for (var k in arr) {
str += '[' + k + ']:' + arr[k].toString() + "\n";
}
return str;
}