JavaScript等于操作异常 [英] JavaScript equal operations anomalies

查看:95
本文介绍了JavaScript等于操作异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一个关于难以理解JavaScript代码的讲座,当然关于JavaScript的弱点是知道== / ===会返回什么。
我在堆栈中找到了很好的答案,很好地涵盖了这个主题 -
在JavaScript比较中应该使用哪个等于运算符(== vs ===)?

I'm working on a lecture about hard to understand JavaScript code and of course on of the weak point of JavaScript is knowing what == / === will return. I found this great answer in stack that covers this subject nicely - Which equals operator (== vs ===) should be used in JavaScript comparisons?

引起我注意的一件事(可能是因为我直到现在才知道它)是你可以使用String Objects而不是原语,你会在你的条件下得到不同的结果 -

one of the things that caught my eyes (probably because I wasn't aware of it until now) was that you can use String Objects instead of primitives and you will get different result in your conditions -

"abc" == new String("abc")    // true
"abc" === new String("abc")   // false

我想测试它并发现一些使用String Objects的不那么直观的结果 -

I wanted to test it and found out a few not so intuitive results using String Objects -

new String("abc") === new String("abc")    // false

甚至

new String("abc") == new String("abc")   // false

at the从我开始这是一个浏览器错误,但我在chrome和Firefox上测试了它。
所以如果有人可以分享更多信息我会非常高兴如何比较文字字符串和字符串对象将是真实的,但比较两个相等字符串对象将是假的

at the beginning I thought this is a browser bug, but I tested it both on chrome and Firefox. So I'd be really happy if some one could share more information how can it be that comparing a literal string and a string object will be truthy but comparing two "equal" string objects will be falsy

推荐答案


比较两个相等字符串对象将是假的

我突出了上面重要的一句话。两个对象引用永远不会彼此相等,除非它们引用完全相同的对象

I've highlighted the important word above. Two object references are never equal to each other unless they refer to exactly the same object.

您正在创建两个<$>的新实例C $ C>字符串。这是两个独立的对象,即使它们具有相同的字符串值。

You're creating two new instances of String. That's two separate objects, even if they do have the same string value.

var s1 = new String("abc"),
    s2 = new String("abc");

s1 === s1; // true
s1 === s2; // false

这一点在规范中由抽象平等算法严格的相等算法


返回 true 如果 x y 指的是同一个对象。否则,返回 false

Return true if x and y refer to the same object. Otherwise, return false.

这篇关于JavaScript等于操作异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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