我有这样一个类,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));
我想查找坐标存储数组中是否存在一个坐标(3,4)。
if ( coordinatesStorage.find(Vector{x:3, y:4}) ) {
gameOver = true;
} // this code does not work
不幸的是,上面提到的是我的蹩脚方法,是无效的,并返回一个Console错误.我有一个C++背景。我正试图将我的Cpp代码转换为JS。
请帮助该代码 找出坐标存储数组中是否存在一个坐标(3,4)。
在 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 更详细的信息。