JavaScript - Why can't I add new attributes to a “string” object?

后端 未结 6 1381
误落风尘
误落风尘 2020-12-19 14:10

I\'ve experimented with JavaScript and noticed this strange thing:

var s = \"hello world!\";
s.x = 5;
console.log(s.x); //undefined

Every t

6条回答
  •  情深已故
    2020-12-19 14:56

    A string in JavaScript isn't an instance of String. If you do new String('my string') then it will be. Otherwise it's a primitive, which is converted to a String object on the fly when you call methods on it. If you want to get the value of the string, you need to call toString(), as shown below:

    var s = new String("hello world!");
    s.x = 5;
    console.log(s.x); //5
    console.log(s); //[object Object]
    console.log(s.toString()); //hello world!
    

提交回复
热议问题