認(rèn)證高級PHP講師
Judging from the code you gave, there is no need to pre-assign the value to string type in the current usage scenario. You can’t go wrong if you don’t preset it.
But there is an essential difference between not assigning a value and assigning an empty string, that is, the type of the variable is changed.
When no assignment is made, it is of type undefined, when the value is null, it is of type null, and when the value is an empty string "", it is of type string.
To be on the safe side, since the expected result of this variable is string type, it is a safe way to specify its type when declaring it.
What if you don’t specify it? That does cause problems sometimes.
The problem mainly occurs when you use this variable to splice other data. This is likely to trigger implicit type conversion, and you will be able to find the difference.
As follows:
var a;
a+"a";
So what is the result? Not "a", but "undefineda".
If a is set to null by default, the result is "nulla".
In your example, res is assigned directly instead of spliced ??with it, so there is no impact if it is not assigned to an empty string, but it is not recommended.
Another example, splice numbers from 0-9, if what you want is also a string, such as "0123456789":
var res;
for (var i = 0; i < 10; i++) {
res+=i;
}
console.log(res);
Is it okay if I don’t declare it? No, res will be converted to number type, but undefined is NaN after conversion, and the final result you get is also NaN.
It is only correct if res is assigned the value "" empty string.
The current case does not need to be predefined as an empty string and can be deleted to improve code readability
Empty strings are generally used in scenarios where a conditional judgment operation is performed on a string or an operation is performed on itself:
First type:
var a = '';
if (xxx) {
a = 'hello';
}
console.log('a'); //這時(shí)如果你不提前定義好a,如果條件不滿足if,那么就不會執(zhí)行,下面調(diào)用變量a的時(shí)候就會undefined
The second type:
var a = '';
a += 2; //這其實(shí)也要調(diào)用變量a,如果不提前定義,那么也是undefined
js預(yù)解析時(shí)會對var關(guān)鍵字定義的變量進(jìn)行預(yù)解析,都會賦值undefined。下面將其賦值為字符串,上面定義的時(shí)候也就將它預(yù)先初始化為一個(gè)空字符串。只聲明var res;,不給它賦值也是可行的。
Personally, I think this was done unintentionally by the author...
If you insist on interpreting it, this is either good or bad. The good thing is that you can intuitively recognize that res is a string variable, which enhances readability; the bad thing is that there is an extra process of object creation and release, and there is a performance loss, although the loss is negligible.