javascript - Regarding the use of empty strings.
PHP中文网
PHP中文网 2017-07-05 10:53:08
0
4
763

PHP中文网
PHP中文网

认证高级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'); //这时如果你不提前定义好a,如果条件不满足if,那么就不会执行,下面调用变量a的时候就会undefined

    The second type:

    var a = ''; a += 2; //这其实也要调用变量a,如果不提前定义,那么也是undefined
      伊谢尔伦
      js预解析时会对var关键字定义的变量进行预解析,都会赋值undefined。下面将其赋值为字符串,上面定义的时候也就将它预先初始化为一个空字符串。只声明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.

          Latest Downloads
          More>
          Web Effects
          Website Source Code
          Website Materials
          Front End Template
          About us Disclaimer Sitemap
          php.cn:Public welfare online PHP training,Help PHP learners grow quickly!