JS judges that the element is a singular way of writing a number. If you need it, refer to it. This is shown in the underscore (1.3.3) Source Code. Its each method
The 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
The 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
The 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
The Code is as follows:
Function isNumber1 (){
Return typeof a = 'number'
}
Or use Object. prototype. toString.
The Code is as follows:
Function isNumber2 (){
Return Object. prototype. toString. call (a) = '[object Number]'
}
Change to this writing method
The Code is as follows:
Function isNumber3 (){
Return a = +
}
Test with various types
The Code is as follows:
Var arr = ['1', true, false, undefined, null, {}, [], 1]
For (var I = 0; iconsole. 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.