为什么 ("foo" === new String("foo")) 在 JavaScript 中评估为 false? [英] Why does ("foo" === new String("foo")) evaluate to false in JavaScript?
问题描述
我本打算在比较字符串值时一直使用 ===(三重等号,严格比较),但现在我发现
I was going to start using === (triple equals, strict comparison) all the time when comparing string values, but now I find that
"foo" === new String("foo")
是假的,与此相同:
var f = "foo", g = new String("foo");
f === g; // false
当然:
f == g; // true
那么是建议字符串比较总是使用==,还是比较之前总是先把变量转成字符串?
So is it recommended to always use == for string comparison, or always convert variables to strings before comparing?
推荐答案
"foo"
是一个字符串 primitive.(这个概念在C#或Java中不存在)
"foo"
is a string primitive. (this concept does not exist in C# or Java)
new String("foo")
是装箱的字符串对象.
new String("foo")
is boxed string object.
===
操作符 对原语和对象的行为不同.
比较原始类型(相同类型)时,如果它们具有相同的值,===
将返回 true.
The ===
operator behaves differently on primitives and objects.
When comparing primitives (of the same type), ===
will return true if they both have the same value.
比较对象时,===
仅当它们引用同一个对象(通过引用进行比较)时才会返回 true.因此,new String("a") !== new String("a")
.
When comparing objects, ===
will return true only if they refer to the same object (comparing by reference). Thus, new String("a") !== new String("a")
.
在您的情况下,===
返回 false,因为操作数的类型不同(一个是原始类型,另一个是对象).
In your case, ===
returns false because the operands are of different types (one is a primitive and the other is an object).
原语根本就不是对象.typeof
运算符不会为原语返回 "object"
.
Primitives are not objects at all.
The typeof
operator will not return "object"
for primitives.
当您尝试访问原始对象的属性(将其用作对象)时,Javascript 语言会将其装箱为一个对象,每次都创建一个新对象.这在规范中有所描述.
When you try to access a property of a primitive (using it as an object), the Javascript language will box it to an object, creating a new object every time. This is described in the specification.
这就是为什么你不能在基元上放置属性:
This is why you cannot put properties on primitives:
var x = "a";
x.property = 2;
alert(x.property) //undefined
每次编写 x.property
时,都会创建一个 不同的 装箱 String
对象.
Each time you write x.property
, a different boxed String
object is created.
这篇关于为什么 ("foo" === new String("foo")) 在 JavaScript 中评估为 false?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!