在javascript中搜索多维坐标数组以获得完全匹配

时间:2022-02-21 21:38:50

I have an array of coordinate points that I am using to run animations and would like to get the current position of an image and determine what index of the array that position is.

我有一个坐标点数组,我用它来运行动画,并希望得到一个图像的当前位置,并确定该位置的数组索引。

var pointArray = [{x:70, y:500},
    {x:120, y:500},
    {x:150, y:500},
    {x:178, y:488},
    {x:193, y:465},
    {x:205, y:440},
    {x:228, y:418},
    {x:255, y:408},
    {x:286, y:405},
    {x:317, y:410},
    {x:345, y:422},
    {x:372, y:438}];

pointArray[indexOf(player1.x)] OR pointArray[indexOf("{x:70, y:500}")] both return -1, the default value for when a search term is not found. What is the proper syntax for searching a multidimensional array?

pointArray [indexOf(player1.x)]或pointArray [indexOf(“{x:70,y:500}”)]都返回-1,即未找到搜索词的默认值。搜索多维数组的正确语法是什么?

Note: the point array above is an abridged version, but in the full version coordinates do have duplicated x or y values, so I need to do more than just search for 1 of the 2 coordinate values.

注意:上面的点数组是删节版本,但在完整版本中坐标确实有重复的x或y值,所以我需要做的不仅仅是搜索2个坐标值中的1个。

1 个解决方案

#1


1  

You would have to do a custom search because your new object (the argument to indexOf()) is different to the ones in the array (unless of course you had a reference to the one you're trying to search for).

您必须进行自定义搜索,因为您的新对象(indexOf()的参数)与数组中的对象不同(除非您当前引用了您要搜索的对象)。

An easy way to do it would be...

一个简单的方法是......

var match = {x:70, y:500};
for (var i = 0; i < pointArray.length; i++) {
     if (match.x == pointArray[i].x && match.y == pointArray[i].y) {
         break;
     }
}

Now, i will be the index of where the result was found. You'd need to handle the case where it wasn't found.

现在,我将成为找到结果的索引。您需要处理未找到它的情况。

#1


1  

You would have to do a custom search because your new object (the argument to indexOf()) is different to the ones in the array (unless of course you had a reference to the one you're trying to search for).

您必须进行自定义搜索,因为您的新对象(indexOf()的参数)与数组中的对象不同(除非您当前引用了您要搜索的对象)。

An easy way to do it would be...

一个简单的方法是......

var match = {x:70, y:500};
for (var i = 0; i < pointArray.length; i++) {
     if (match.x == pointArray[i].x && match.y == pointArray[i].y) {
         break;
     }
}

Now, i will be the index of where the result was found. You'd need to handle the case where it wasn't found.

现在,我将成为找到结果的索引。您需要处理未找到它的情况。