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; } |