我有这门课如下。x 和 y 是二维坐标class Vector { constructor(x, y) { this.x = x; this.y = y; }}我有一个数组来存储坐标 x 和 yconst coordinatesStorage = [];coordinatesStorage.push(new Vector(1, 2));coordinatesStorage.push(new Vector(3, 4));coordinatesStorage.push(new Vector(4, 6));我想查找坐标存储数组中是否存在坐标(3,4)if ( coordinatesStorage.find(Vector{x:3, y:4}) ) { gameOver = true;} // this code does not work不幸的是,上面提到的是我的蹩脚方法,它无效并且返回控制台错误。我有 C++ 背景。我正在尝试将我的 Cpp 代码转换为 JS。请帮助该代码以查找坐标存储数组中是否存在坐标(3,4)
1 回答

一只甜甜圈
TA贡献1836条经验 获得超5个赞
find
数组上的函数接收一个函数作为其第一个参数。该函数接收对数组中元素的引用,然后您必须返回true
或false
获取该元素。如果您希望find
函数将该元素作为找到的元素返回,则返回true
. 例如,这样的事情应该可以工作:
if (coordinatesStorage.find(v => v.x === 3 && v.y === 4)) {
这表明它应该返回元素属性coordinatesStorage
所在的第一个元素,并且它的为。x
3
y
4
请注意,该v =>
部分是箭头函数表达式的开头,其中v
是函数的参数,表示数组中正在测试的元素。它也可以扩展为像这样的常规函数定义:
function vectorPredicate(vector) { return vector.x === 3 && vector.y === 4; }
然后,您也可以将该定义的函数传递给find
调用,它的工作方式相同:
if (coordinatesStorage.find(vectorPredicate)) {
查看 MDN 关于Array.prototype.find的文章以获取更多详细信息。
添加回答
举报
0/150
提交
取消