简体   繁体   中英

Comparison gives different results in Coffeescript/Javascript and Ruby

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?

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 if x == y for each x in itself and y in the other array.

If you want to emulate the Ruby behavior, it's quite simple to write a function to do so:

deepEquals = (arr1, arr2) ->
  return false unless arr1.length is arr2.length
  for i in [0...arr1.length]
    if arr1[i] instanceof Array and arr2[i] instanceof Array
      return false unless deepEquals(arr1[i], arr2[i])
    else
      return false if arr1[i] isnt arr2[i] 
  true

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. So

[42] == [42]; // false. Different objects
var x = [42];
var y = [42];
x == y;       // false. Same check as [42] == [42]
x == x;       // true.  Same object

The literal 42 is a primitive type and compares by value.

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.

In JavaScript

[42] == [42]

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:

42 == 42

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM