Javascript 如何在包含坐标对的数组上使用find方法?

Javascript 如何在包含坐标对的数组上使用find方法?,javascript,arrays,find,Javascript,Arrays,Find,我的课程如下。x和y是二维坐标 class Vector { constructor(x, y) { this.x = x; this.y = y; } } 我有一个数组来存储坐标x和y const coordinatesStorage = []; coordinatesStorage.push(new Vector(1, 2)); coordinatesStorage.push(new Vector(3, 4)); coordinatesStorage.push(n

我的课程如下。x和y是二维坐标

class Vector {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }
}
我有一个数组来存储坐标x和y

const coordinatesStorage = [];

coordinatesStorage.push(new Vector(1, 2));
coordinatesStorage.push(new Vector(3, 4));
coordinatesStorage.push(new Vector(4, 6));

我想知道CoordinationsStorage数组中是否存在坐标(3,4)

if ( coordinatesStorage.find(Vector{x:3, y:4}) ) {
    gameOver = true;
}     // this code does not work
不幸的是,上面提到的是我的lame方法,它是无效的,并且返回一个控制台错误。 我有C++背景。我正在尝试将我的Cpp代码转换为JS


请使用该代码帮助查找CoordinationsStorage数组中是否存在坐标(3,4)

数组上的
find
函数接收一个函数作为其第一个参数。该函数接收对数组中某个元素的引用,然后必须为该元素返回
true
false
。如果希望
find
函数将该元素作为find元素返回,则返回
true
。例如,类似这样的方法应该可以工作:

if (coordinatesStorage.find(v => v.x === 3 && v.y === 4)) {
这表明它应该返回
坐标存储中的第一个元素,其中元素的
x
属性为
3
,其
y
属性为
4

注意,
v=>
部分是一个数组的开始,其中
v
是函数的一个参数,表示数组中正在测试的元素。也可以将其扩展为常规函数定义,如下所示:

function vectorPredicate(vector) {
    return vector.x === 3 && vector.y === 4;
}
然后,也可以将定义的函数传递到
find
调用中,其工作方式相同:

if (coordinatesStorage.find(vectorPredicate)) {

查看MDN的文章以获取更详细的信息。

好的问题与此类似,它与C++中的函数指针类似。在这种情况下,该函数将导致
find
返回数组中第一个元素,该元素为函数返回
true
<如果使用该函数测试的元素均未返回
true
,则code>find
将返回
undefined