Reputation: 149
I have a loop like the following:
for (var i = 0; i < arr.length; i++) {
console.log(arr);
// rest of the code does not touch 'arr'
...
}
However, in the browser console (Chrome), I keep getting this:
Array[0]
length: 0
__proto__: Array[0]
as the output of console.log(arr)
, which suggests that there is nothing in arr
. But then how is it possible that the logging statement gets executed?!
Upvotes: 1
Views: 63
Reputation: 16468
Probably, the array is empty at the end of the script, because chrome console show you the current state of the object (does change when the object itself change) when it have been opened after script execution. (I think it's an issue)
To reproduce this:
var arr = [1];
for (var i = 0; i < arr.length; i++) {
console.log(arr);
}
arr.pop(); // empty the array
http://jsfiddle.net/47nrc/ (only for chrome)
execute it with console closed, then when you open it you could see Array[0]
One solution could be to log a string representation of the array:
console.log(arr.join());
See also: https://code.google.com/p/chromium/issues/detail?id=50316
Upvotes: 1
Reputation: 28417
See this fiddle: http://jsfiddle.net/r9exf/
var arr = [];
for (var i = 0; i < arr.length; i++) {
console.log("arr = " + arr);
// rest of the code does not touch 'arr'
}
compared to:
var arr2 = [1,2,3];
for (var i = 0; i < arr2.length; i++) {
console.log("arr2 = " + arr2);
// rest of the code does not touch 'arr'
}
Your code (assuming what you have provided is what you have), is just working fine. It does not enter the loop (see the first case and compare with second in the fiddle).
So, it must be somewhere else in your code which is logging this array.
Upvotes: 0