最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Test object equality in CoffeeScript? - Stack Overflow

programmeradmin3浏览0评论

Is there a simple way to test equality of objects in CoffeeScript?

Or more correctly - test if the properties of two objects are identical.

With these objects:

obj1 =
  name: "John Doe"
  age: "3.14"

obj2 =
  name: "John Doe"
  age: "3.14"

This evaluates false, as expected:

obj1 == obj2

For now I'm using Underscore's isEqual

Is there a simple way to test equality of objects in CoffeeScript?

Or more correctly - test if the properties of two objects are identical.

With these objects:

obj1 =
  name: "John Doe"
  age: "3.14"

obj2 =
  name: "John Doe"
  age: "3.14"

This evaluates false, as expected:

obj1 == obj2

For now I'm using Underscore's isEqual

Share Improve this question edited Nov 22, 2012 at 0:53 mnorrish asked Nov 21, 2012 at 22:04 mnorrishmnorrish 4795 silver badges11 bronze badges 2
  • 3 What's wrong with _.isEqual? You need to perform some sort of deep equality. – Matt Ball Commented Nov 21, 2012 at 22:05
  • There's nothing wrong with the Underscore method but I'd be interested in a short-hand language feature. – mnorrish Commented Nov 22, 2012 at 2:28
Add a ment  | 

2 Answers 2

Reset to default 11

Nope. CoffeeScript doesn't provide this as a language feature, so using a library like Underscore.js is your best option.

You can use the old standby:

JSON.stringify(obj1) == JSON.stringify(obj2)

Which will do the job - but may be too inefficient for some jobs.

You could also turn your arbitrary objects into a class and provide an equals method on the class.

class Person
  constructor: (@name, @age) ->
  
  equals: (other) -> @name == other.name && @age == other.age 
发布评论

评论列表(0)

  1. 暂无评论