Recently I found myself writing JavaScript code is bloated, so I began to study the shorthand method of JavaScript. This will make our JavaScript code look refreshing and also improve our technology. So what's the shorthand for an empty judgment?
The following is a shorthand method for determining null.
The code is as follows |
Copy Code |
if (variable1!== null | | variable1!== undefined | | variable1!== ") { var variable2 = variable1; } |
The above means that if variable1 is not an empty object, or undefined, or not equal to an empty string, declare a variable2 variable and assign the Variable1 to Variable2. That is, if the variable1 exists then the value of the variable1 is assigned to the Variable2, or an empty string if it does not exist. Like the following shorthand code.
Shorthand code:
The code is as follows |
Copy Code |
var variable2 = Variable1 | | '';
|
The following are not the correct methods:
The code is as follows |
Copy Code |
var exp = null; if (exp = null) { Alert ("is null"); }
|
When exp is undefined, it will also get the same result as NULL, although null and undefined are different. Note: This method can be used to determine both null and undefined.
The code is as follows |
Copy Code |
var exp = null; if (!EXP) { Alert ("is null"); } |
If exp is undefined, or the number zero, or false, the result will be the same as NULL, although NULL is not the same as the two. Note: This method can be used to determine both null, undefined, number 0, and false.
The code is as follows |
Copy Code |
var exp = null; if (typeof exp = "NULL") { Alert ("is null"); } |
For backward compatibility, when EXP is null, typeof null always returns object, so this cannot be judged.
The code is as follows |
Copy Code |
var exp = null; if (IsNull (exp)) { Alert ("is null"); } |
Determines whether a string is empty
s matches any whitespace character, including spaces, tabs, page breaks, and so on. equivalent to [FNRTV]. In many cases, you can use length to directly determine whether the string is empty, as follows:
The code is as follows |
Copy Code |
var strings = '; if (string.length = 0) { Alert (' cannot be empty '); } |
But what if the user enters a space, tab, and page break? In this case, it is not empty, but such data is not what we want it.
In fact, we can use regular expressions to remove these "empty" symbols to determine
The code is as follows |
Copy Code |
var strings = '; if (Strings.replace (^s*) | ( s*$)/g, ""). Length ==0) { Alert (' cannot be empty '); }
|
s lowercase s is, matching any whitespace characters, including spaces, tabs, page breaks, and so on. equivalent to [FNRTV].
Judge as empty how to abbreviate, for you to introduce here, hope the above method can be helpful to everyone. The above view is a personal point of view, if you have any questions you can contact us, we would like to study with you.