JavaScript to determine whether a variable is empty a custom function to share _javascript tips

Source: Internet
Author: User

JavaScript itself does not determine whether a variable is a null value function, because the variable may be string,object,number,boolean and other types, different types, the method of judgment is also different. So in the article wrote a function to determine whether the JS variable null value, if it is undefined, null, ', nan,false,0,[],{}, white string, all return True, otherwise return false

Copy Code code as follows:

function IsEmpty (v) {
Switch (typeof v) {
Case ' undefined ':
return true;
Case ' string ':
if (V.replace (^[\t\n\r]*) | ( [\t\n\r]*$)/g, '). Length = = 0) return true;
Break
Case ' Boolean ':
if (!V) return true;
Break
Case ' number ':
if (0 = = V | | isNaN (v)) return true;
Break
Case ' object ':
if (null = = V | | v.length = 0) return true;
for (var i in V) {
return false;
}
return true;
}
return false;
}

Test:

Copy Code code as follows:

IsEmpty ()//true
IsEmpty ([])//true
IsEmpty ({})//true
IsEmpty (0)//true
IsEmpty (Number ("abc"))//true
IsEmpty ("")//true
IsEmpty ("")//true
IsEmpty (False)//true
IsEmpty (NULL)//true
IsEmpty (undefined)//true

Related Article

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.