I have found some code from Underscore.js
_.map = _.collect = function(obj, iterator, context) {
var results = [];
if (obj == null) return results;
if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context);
each(obj, function(value, index, list) {
results[results.length] = iterator.call(context, value, index, list);
});
if (obj.length === +obj.length) results.length = obj.length;
return results;
};
I would like to know what if (obj.length === +obj.length)
does?
A unary operation is an operation with only one operand. This operand comes either before or after the operator. Unary operators are more efficient than standard JavaScript function calls. Additionally, unary operators can not be overridden, therefore their functionality is guaranteed. Operator.
Unary operators: are operators that act upon a single operand to produce a new value. Types of unary operators: unary minus(-) increment(++)
A unary operation is an operation with only one operand. As unary operations have only one operand, they are evaluated before other operations containing them. Common unary operators include Positive ( + ) and Negative ( - ).
An operation that has only one input. Example: the square root function. √(16) = 4 has just one input "16" to produce an output of 4. There are many more: factorial, sine, cosine, etc.
+length
is a method to convert anything to a number.
If it's a number, the value doesn't change, and the comparison returns true.
If it's not a number, the assertion is false.
That's the unary + operator. This website has a great article on its uses with the different data types in javascript.
http://xkr.us/articles/javascript/unary-add/
I'll steal the introduction, but it is really worth reading if you are into javascript.
In JavaScript it is possible to use the + operator alone before a single element. This indicates a math operation and tries to convert the element to a number. If the conversion fails, it will evaluate to NaN. This is especially useful when one wants to convert a string to a number quickly, but can also be used on a select set of other types.
The unary + operator, when used on types other than string, will internally attempt to call valueOf() or toString() (in that order) and then attempt to convert the result to a number. Thusly, the unary + operator can successfully convert many of the native JS types with certain restrictions:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With