I just read the underscope source code, and cannot get the point from this code:
_.each = _.forEach = function(obj, iterator, context) {
if (obj == null) return obj;
iterator = createCallback(iterator, context);
var i, length = obj.length;
if (length === +length) { // why +length?
for (i = 0; i < length; i++) {
iterator(obj[i], i, obj);
}
} else {
var keys = _.keys(obj);
for (i = 0, length = keys.length; i < length; i++) {
iterator(obj[keys[i]], keys[i], obj);
}
}
return obj;
};
why length===+length ? I guess this used for force to convert if length is not a number? Could somebody give me a hand?
length is a property of arrays in JavaScript that returns or sets the number of elements in a given array.
length is a property of array, not a method if it was a method getting the length of an array would be of O(n), but by keeping it as a property its O(1).
A Function object's length property indicates how many arguments the function expects, i.e. the number of formal parameters. This number excludes the rest parameter and only includes parameters before the first one with a default value.
Though arrays are objects in Java but length is an instance variable (data item) in the array object and not a method. So, we cannot use the length() method to know the array length.
+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.
What is unary + used for in Javascript?
+length
converts any value of length to a number (NaN if not possible).
So length===+length
just tests that length
is really a number (not a string that could be converted to a number), and that it's not NaN (which isn't equal to itself).
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