JavaScript string initialization

后端 未结 5 640
暗喜
暗喜 2021-02-04 08:39

In JavaScript, from my understanding, the below are all same:

var carter2 = new String();
var carter2 = \'\';
var carter2 = \"\";

Which one is

5条回答
  •  没有蜡笔的小新
    2021-02-04 09:05

    Don't use

    var str = new String();
    

    Because

    var str = new String("dog");
    var str2 = new String("dog"); 
    str == str2; // false
    

    But

    var str = "dog";
    var str2 = "dog"; 
    str == str2; // true
    

    However, because of type coercion, the following works (Thanks to Rocket for pointing it out)

    var str = new String("dog");
    var str2 = "dog"; 
    str == str2; // true
    

    Single and double quotes don't matter, except for what quotes need to be escaped. Many others have noted that single quotes are better when creating HTML strings, since XHTML expects attributes to have double quotes, and you won't need to escape them.

提交回复
热议问题