JavaScript string initialization

后端 未结 5 635
暗喜
暗喜 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:06

    When doing new String(), you are not being returned a string primitive, but a String object.

    For all intents and purposes it acts like a string primitive, but there are cases where it won't. For example:

    var a = new String('body');
    jQuery(a); // This will *not* function as expected
               // This will make a jQuery object containing a "String" object
               // It will NOT treat it as a selector string
    

    Also when comparing things, there may be problem. When you compare objects in JavaScript, it's only true if they are the same exact object, not just the same value. Example:

    var a = new String('test');
    var b = new String('test');
    var c = a;
    var d = 'test';
    
    a === b; // false, a and b are different objects (a == b is also false)
    c === a; // true, a is the same object as c
    c === b; // false, c (which is a) is a different object than b
    d === a; // false, d is a primitive and a is an object, they are not equal
    'test' === d; // true, they are both string primitives
    
    d == a; // true, this uses "==" so only value is compared, not type
    

    You can use .valueOf() to convert a String object to a string primitive.

    new String('test').valueOf() === 'test'; // true
    

    So, I highly suggest using var a = '' or var a = "". As for single quotes vs. double quotes, there is no difference. Consider this example:

    var a = "My name is Joe O'Ryan";
    var b = 'My name is Joe O\'Ryan'; // need to escape the '
    var c = 'Joe said: "Hi"';
    var d = "Joe said \"HI\""; // need to escape the "
    

    So, it's up to you whether to use ' or ", but I suggest those over new String().

提交回复
热议问题