Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/429.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 设置ECMA6 JS中对象的可比性_Javascript_Set_Comparator_Equality_Ecmascript 6 - Fatal编程技术网

Javascript 设置ECMA6 JS中对象的可比性

Javascript 设置ECMA6 JS中对象的可比性,javascript,set,comparator,equality,ecmascript-6,Javascript,Set,Comparator,Equality,Ecmascript 6,我一直在使用集合来存储和检索表示坐标的简单对象 // Creates a point in hex coordinates function hexPoint(q, r) { this.q = q; this.r = r; } 我多次生成这些点,以便有容易传递的坐标对,但我希望能够以不存储重复坐标的方式存储它们 // Creates a point in hex coordinates function hexPoint(q, r) { this.q = q

我一直在使用集合来存储和检索表示坐标的简单对象

// Creates a point in hex coordinates
  function hexPoint(q, r) {
    this.q = q;
    this.r = r;
  }
我多次生成这些点,以便有容易传递的坐标对,但我希望能够以不存储重复坐标的方式存储它们

// Creates a point in hex coordinates
  function hexPoint(q, r) {
    this.q = q;
    this.r = r;
  }

ECMA 6集合对象依赖于引用来测试对象的相等性,因此我想知道是否有一种方法可以为这个集合提供一个可比较的函数,以便允许它测试具有相同字段的新对象的相等性。否则,我还能做些什么来避免重新实现这个数据结构吗

为什么不添加一个
isEqual(其他点)
?它可能看起来像:

function HexPoint(q, r) {
  this.q = q;
  this.r = r;
}

HexPoint.prototype.isEqual = function(otherPoint) {
  return this.q === otherPoint.q && this.r === otherPoint.r;
}
然后,您可以使用以下工具创建六角点的实例:

var point = new HexPoint(...);
if (point.isEqual(someOtherPoint)) {
  ...
}

A指出还不存在本机选项。

集合能否使用isEqual函数执行其相等性检查?据我所知,set的实现只检查引用,不执行任何其他检查。我希望集合能够保持其自身的唯一性,而无需我进行检查。@MichaelVonHippel我认为如果需要,您必须构建一个say a UniqueSet类。如果
对象
已经存在,它将检查
添加
。如果使用
HexPoint
,您可能希望添加一个类似于上面的
isEqual
并使用它。不幸的是,执行该检查似乎不需要添加复杂性(因为无论如何我都必须迭代所有现有元素)我想另一种选择是对所有的hexPoint使用工厂,或者简单地创建我自己的实现哈希的集合。普通对象没有重复,您可以使用数字作为键,将q+r粘在一起生成一个“唯一”键,您可以在返回新对象之前在hexPoint()中查找该键。