且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

javascript字符串类型和字符串对象之间的区别?

更新时间:2022-06-22 05:39:25

字符串是JS中的值类型,因此它们不能附加任何属性任何尝试访问它们的属性都是技术上执行JS [[ToObject]]转换(本质上是新的String)。

Strings are a value type in JS, so they can't have any properties attached to them, no prototype, etc. Any attempt to access a property on them is technically performing the JS [[ToObject]] conversion (in essence new String).

简单方法区分差异的是(在浏览器中)

Easy way of distinguishing the difference is (in a browser)

a = "foo"
a.b = "bar"
alert("a.b = " + a.b); //Undefined

A = new String("foo");
A.b = "bar";
alert("A.b = " + A.b); // bar

此外,

"foo" == new String("foo")

is是的,它只是真实的,因为==运算符的隐式类型转换

is true, it is only true due to the implicit type conversions of the == operator

"foo" === new String("foo")

将失败。