Each implementation in the underscore.js library

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; } } } }; 
+6
source share
1 answer

It:

 +obj.length 

... will do the conversion of toNumber to length .

They seem to be sure that length refers to the number, doing the toNumber conversion and checking that it still remains the same number after the conversion.

If so, they assume it is an array, or at least an Array object for iteration.

If not, they assume that the numbering of all pairs of key values ​​is desired.

 var obj = { length:null, someprop:'some value' }; obj.length === +obj.length; // false, so do the enumeration 
 var obj = { length: 2, "0":'some value', "1":'some other value' }; obj.length === +obj.length; // true, not an actual Array, // but iteration is still probably wanted 

Of course, you can have an object with the length property, which is a primitive number, but still intends to list the properties.

 var obj = { length: 2, "prop1":'some value', "prop2":'some other value' }; obj.length === +obj.length; // true, it will iterate, but it would // seem that enumeration is intended 
+5
source

Source: https://habr.com/ru/post/894004/


All Articles