Coffeescript/Javascript 和 Ruby 中的比较给出了不同的结果
示例:
[42] == [42]
比较的结果给出不同的结果:
CS/JS: false
Ruby: true
另一方面:
42 == 42
给出结果:
CS/JS: true
Ruby: true
这背后的原因是什么?
Example:
[42] == [42]
The result of the comparison gives different results:
CS/JS: false
Ruby: true
On the other hand:
42 == 42
gives the result:
CS/JS: true
Ruby: true
What is the reasoning behind this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
其他回答者很好地解释了 JavaScript/CoffeeScript 相等语义。 (CoffeeScript 的
==
编译为 JavaScript 更严格的===
,但这在这种情况下没有区别。)Ruby 的情况更复杂:Ruby 中的一切都是对象,因此每个对象都有一个
==
方法,原则上它可以做任何事情。对于数组,它会查看另一个数组,检查它是否具有相同的长度,然后检查每个x
本身是否x == y
以及 < code>y 在另一个数组中。如果您想模拟 Ruby 行为,编写一个函数来执行此操作非常简单:
The other answerers have done a good job of explaining the JavaScript/CoffeeScript equality semantics. (CoffeeScript's
==
compiles to JavaScript's stricter===
, but that makes no difference in this case.)The Ruby case is more complex: Everything in Ruby is an object, and so every object has a
==
method which, in principle, could do anything. In the case of arrays, it looks at the other array, checks if it has the same length, and then checks ifx == y
for eachx
in itself andy
in the other array.If you want to emulate the Ruby behavior, it's quite simple to write a function to do so:
对于 Javascript 情况,比较是根本不同的。
每个
[42]
都是一个新数组,数组不会在结构上进行比较,它们只是检查它们是否是同一个对象。所以文字 42 是一个原始类型并按值进行比较。
For the Javascript case the comparisons are fundamentally different.
Each
[42]
is a new array and arrays don't compare structurally they simply check to see if they are the same object. SoThe literal 42 is a primitive type and compares by value.
在 JavaScript 中,数组是通过引用而不是值进行比较的。
[42]
和[42]
是不同的实体(尽管是彼此的克隆),因此不相等。不幸的是,42 是一切问题的答案这一事实与此无关。
In JavaScript, arrays are compared by reference, not by value.
[42]
and[42]
are different entities (albeit clones of one another) and therefore not equal.The fact that 42 is the answer to everything is, unfortunately, not relevant here.
在 JavaScript 中
,“这两个数组是同一个对象吗?” (不,他们不是),这与问“这两个数组是否包含相同的元素?”不同。
另一方面:
“这两个数字原语按值比较是否相等?”
(注意:这是对 JavaScript 所做操作的过度简化,因为
==
运算符将尝试将两个操作数转换为相同类型;与===
运算符相反。 )In JavaScript
says "Are these two arrays the same object?" (no they're not), which is not the same as asking "Do these two arrays contain the same elements?"
On the other hand:
"Are these two number primitives equal comparing by value?"
(Note: this is an oversimplification of what JavaScript is doing because the
==
operator will attempt to convert both operands to the same type; contrast with the===
operator.)