This question already has answers here:
What's the point of new String(“x”) in JavaScript?
                            
                                (9个答案)
                            
                    
                4年前关闭。
        

    

我对wrapper objects for primitives感到非常困惑。例如,字符串基元和使用字符串包装器对象创建的字符串。

var a = "aaaa";
var b = new String("bbbb");
console.log(a.toUpperCase()); // AAAA
console.log(b.toUpperCase()); // BBBB
console.log(typeof a);        // string
console.log(typeof b);        // object


两者都可以访问String.prototype方法,并且看起来就像字符串文字一样。但是一个不是字符串,而是一个对象。 ab的实际区别是什么?为什么要使用new String()创建字符串?

最佳答案

原始字符串不是对象。对象字符串是一个对象。

基本上,这意味着:


对象字符串是通过引用而不是它们包含的字符串进行比较的

"aaa" === "aaa";                         // true
new String("aaa") === new String("aaa"); // false

对象字符串可以存储属性。

function addProperty(o) {
  o.foo = 'bar'; // Set a property
  return o.foo;  // Retrieve the value
}
addProperty("aaa");             // undefined
addProperty(new String("aaa")); // "bar"

关于javascript - Javascript中字符串原始对象和字符串包装对象之间的区别,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30984463/

10-12 00:06
查看更多