为什么(“foo”=== new String(" foo"))在JavaScript中评估为false? [英] Why does ("foo" === new String("foo")) evaluate to false in JavaScript?

查看:179
本文介绍了为什么(“foo”=== new String(" foo"))在JavaScript中评估为false?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在比较字符串值时,我会一直开始使用===(三等号,严格比较),但现在我发现

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")

为false ,与此相同:

is false, and same with this:

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是一个字符串原始。 (这个概念在C#或Java中不存在)

"foo" is a string primitive. (this concept does not exist in C# or Java)

new String(foo)是盒装字符串对象。

=== 运算符在基元和对象上表现不同

比较基元(相同类型)时, ===如果都具有相同的值,则返回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").

在你的case, === 返回false,因为操作数的类型不同(一个是基元,另一个是对象)。

In your case, === returns false because the operands are of different types (one is a primitive and the other is an object).

原语根本不是对象。

typeof 运算符不会返回对象用于基元。

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屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆