Recently, I suddenly found that the JavaScript code I wrote was quite bloated, so I started to study the abbreviation method of JavaScript. This way, our JavaScript code can look refreshing, and also improve our technology. So how to abbreviate it if it is empty?
The following is the abbreviation method for judging that it is empty.
The code is as follows
The code copy is as follows:
if (variable1 !== null || variable1 !== undefined || variable1 !== '') {
var variable2 = variable1;
}
The above means that if variable1 is not an empty object, or is undefined, or is not equal to an empty string, then declare a variable2 variable and assign variable1 to variable2. That is to say, if variable1 exists, then the value of variable1 is assigned to variable2. If it does not exist, it is an empty string. As in the abbreviation code below.
Abbreviation code:
The code is as follows
The code copy is as follows:
var variable2 = variable1 || '';
Here are the incorrect methods:
The code is as follows
The code copy is as follows:
var exp = null;
if (exp == null)
{
alert("is null");
}
When exp is undefined, the same result as null is also obtained, although null and undefined are different. Note: This method can be used when judging null and undefined at the same time.
The code is as follows
The code copy is as follows:
var exp = null;
if (!exp)
{
alert("is null");
}
If exp is undefined, or the number zero, or false, you will also get the same result as null, although null is different from the two. Note: This method can be used when judging null, undefined, numeric zero, and false at the same time.
The code is as follows
The code copy is as follows:
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
The code copy is as follows:
var exp = null;
if (isNull(exp))
{
alert("is null");
}
Determine whether the string is empty
s matches any whitespace characters, including spaces, tabs, page breaks, etc. Equivalent to [fnrtv]. In many cases, length is used to directly determine whether a string is empty, as follows:
The code is as follows
The code copy is as follows:
var strings = '';
if (string.length == 0)
{
alert('can't be empty');
}
But what if the user enters spaces, tabs, or page renewals? In this case, it is not empty, but such data is not what we want.
In fact, you can use regular expressions to remove these "empty" symbols to judge
The code is as follows
The code copy is as follows:
var strings = ' ';
if (strings.replace(/(^s*)|(s*$)/g, "").length ==0)
{
alert('can't be empty');
}
s The lowercase s is to match any whitespace characters, including spaces, tabs, page breaks, etc. Equivalent to [fnrtv].
I will tell you how to abbreviate it as empty. I will introduce it to you here. I hope the above method can be helpful to you.