Code for determining whether the value/variable is null using Javascipt

Source: Internet
Author: User

To determine whether the present value of a variable is null in js, we can directly undefined, null, \ ', false, 0, [], {} to operate the variable. Below I will show you several instances, for more information, see.

Method 1:

The Code is as follows: Copy code

Var keyVal = $ ("# key"). val ();
If (keyVal = undefined | keyVal = "" | keyVal = null ){
Alert ("the value of the hidden field is empty ");
}

This method is not efficient and is not recommended.

Method 2:

The Code is as follows: Copy code


Var keyVal = $ ("# key"). val ();
If (keyVal. length = 0 ){
Alert ("the value of the hidden field is empty ");
}

This method is efficient.

// Function

The Code is as follows: Copy code

Function empty (mixed_var ){
Var key;
 
If (mixed_var = "" | mixed_var = 0 | mixed_var = "0" | mixed_var = null | mixed_var = false | typeof mixed_var = 'undefined ') {
Return true;
}
 
If (typeof mixed_var = 'object '){
For (key in mixed_var ){
Return false;
}
Return true;
}
 
Return false;
}

Determines whether the variable is null: undefined, null, '', false, 0, [], {}. true is returned. Otherwise, false is returned.

The Code is as follows:

The Code is as follows: Copy code

Function empty (v ){
Switch (typeof v ){
Case 'undefined': return true;
Case 'string': if (trim (v). length = 0) return true; break;
Case 'boolean': if (! V) return true; break;
Case 'number': if (0 = v) return true; break;
Case 'object ':
If (null = v) return true;
If (undefined! = V. length & v. length = 0) return true;
For (var k in v) {return false;} return true;
Break;
}
Return false;
}

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.