I came across an unexpected behavior in _.forEach(). Take the following code:
var data = { length: 3 };
_.forEach(data, function(value, key) {
console.log(value, key);
});
This outputs:
undefined 0
undefined 1
undefined 2
While I would expect it to output:
3 "length"
For example, when I do:
var data = { foo: 3 };
_.forEach(data, function(value, key) {
console.log(value, key);
});
I get:
3 "foo"
It appears the logic for determining if { length: 3 } is an array or an object is incorrect and is causing us to iterate over an array of [undefined, undefined, undefined]. I see the incorrect assumption pretty clearly in the isArrayLike() method of the Underscore build, but am not sure exactly where this code lives in the actual lodash source. I assume _.forEach() is not the only method susceptible to this issue.
Hi @jwngr! This is by design. _.each is a "Collection" method and as such prioritizes array-like objects over object iteration. If you're wanting just object iteration try _.forOwn or _.forIn.
Sweet, thanks for the quick response! I wasn't aware of that nuance but that seems like a sensible design decision. _.forOwn() is exactly what I need!
This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.
Most helpful comment
Hi @jwngr! This is by design.
_.eachis a "Collection" method and as such prioritizes array-like objects over object iteration. If you're wanting just object iteration try_.forOwnor_.forIn.