为什么JavaScript中新的Number(2)!= new String(" 2") [英] Why does new Number(2) != new String("2") in JavaScript

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

问题描述

以下评估为 true

new Number(2) == 2
new String("2") == "2"

显然,但以下情况也是如此:

Obviously, but so do the following:

"2" == 2
new Number(2) == "2"
new String("2") == 2

所以有人可以解释清楚为什么他跟随评估 false

So can someone explain clearly why he following evaluates false?

new Number(2) == new String("2")


推荐答案

因为JavaScript同时具有 primitive object 版本的数字和字符串(和布尔值)。 new Number new String create object 版本,当你使用 == 使用对象引用,您要比较对象引用,而不是值。

Because JavaScript has both primitive and object versions of numbers and strings (and booleans). new Number and new String create object versions, and when you use == with object references, you're comparing object references, not values.

new String(x ) String(x)是根本不同的东西(对于 Number ,这是正确的好)。 使用 new 运算符,您将创建一个对象。 没有 运算符,您正在进行类型强制 —例如字符串(2)为您提供2数字(2)给你 2

new String(x) and String(x) are fundamentally different things (and that's true with Number as well). With the new operator, you're creating an object. Without the new operator, you're doing type coercion — e.g. String(2) gives you "2" and Number("2") gives you 2.

这篇关于为什么JavaScript中新的Number(2)!= new String(" 2")的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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