Share the singular Writing Method for JS to determine the element as a number

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.