One of my co-workers created a silly bug in mongo mapreduce, he should have created an object but actually passed the string "{}"
. The weird thing was the script hasn't crashed but actually iterated over the string, so I did some investigation and found the following:
The script x="bla"; for (i in x) { alert(i); };
works the following way with different browsers:
- IE(8): - (no alerts)
- Chrome: 0 1 2
- Firefox (an older one): 0 1 2 vBlength
- Firefox 5: 0 1 2
- MongoDB: 0 1 2 trim ltrim rtrim
I know perfectly well it's not a valid syntax, just pure curiosity, does anybody know why browsers behave the way they do? I'm especially interested in MongoDB's behaviour.
1 Answer 1
Actually, that is completely valid syntax.
Using the for...in loop in JavaScript will not only loop over arrays but also properties (i is simply an index, not an actual value in the array).
Check out the documentation at the Mozilla Developer Network:
Their example should make things more clear.