This is shown in the underscore (1.3.3) Source Code. Its each method
Copy codeThe Code is as follows:
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 (iterator. call (context, obj [I], I, obj) === breaker) return;
}
} Else {
For (var key in obj ){
If (_. has (obj, key )){
If (iterator. call (context, obj [key], key, obj) === breaker) return;
}
}
}
};
This method contains
Copy codeThe Code is as follows: if (obj. length = + obj. length)
I haven't understood it for a long time. After being pointed out by someone else, this sentence is equivalent
Copy codeThe Code is as follows: if (typeof obj. length = 'number ')
It is used to determine whether an element is of the numeric type. Typeof and Object. prototype. toString are common methods. The last one is uncommon and hard to understand.
Some libraries have tool functions for type determination, such
Copy codeThe Code is as follows:
Function isNumber1 (){
Return typeof a = 'number'
}
Or use Object. prototype. toString.
Copy codeThe Code is as follows:
Function isNumber2 (){
Return Object. prototype. toString. call (a) = '[object Number]'
}
Change to this writing method
Copy codeThe Code is as follows:
Function isNumber3 (){
Return a = +
}
Test with various types
Copy codeThe Code is as follows:
Var arr = ['1', true, false, undefined, null, {}, [], 1]
For (var I = 0; I <arr. length; I ++ ){
Console. log (isNumber3 (arr [I])
}
Only the last entry of the array is true. That is, only the number type a = + a is true.
Why not use typeof, because the character string needs to traverse all characters theoretically, and the performance is proportional to the string length.