亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

javascript - Regarding the use of empty strings.
PHP中文網(wǎng)
PHP中文網(wǎng) 2017-07-05 10:53:08
0
4
930

PHP中文網(wǎng)
PHP中文網(wǎng)

認(rèn)證高級PHP講師

reply all(4)
過去多啦不再A夢

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;,不給它賦值也是可行的。
曾經(jīng)蠟筆沒有小新

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template