The question is about implementing "every" function that I found in the source code of underscore.js (source below).
First, can someone explain what the string "else if (obj.length === + obj.length)" checks.
Secondly, can someone explain why hasOwnProperty.call (obj, key) is used, and not obj.hasOwnProperty? This is because the one accepted by obj cannot implement hasOwnProperty (which I thought every javascript object did)
Any ideas appreciated. Thanks.
// The cornerstone, an `each` implementation, aka `forEach`. // Handles objects with the built-in `forEach`, arrays, and raw objects. // Delegates to **ECMAScript 5** native `forEach` if available. var each = _.each = _.forEach = function(obj, iterator, context) { if (obj == null) return; if (nativeForEach && obj.forEach === nativeForEach) { obj.forEach(iterator, context); } else if (obj.length === +obj.length) { for (var i = 0, l = obj.length; i < l; i++) { if (i in obj && iterator.call(context, obj[i], i, obj) === breaker) return; } } else { for (var key in obj) { if (hasOwnProperty.call(obj, key)) { if (iterator.call(context, obj[key], key, obj) === breaker) return; } } } };
source share