我正在尝试弄清楚如何反转 for 循环,这有点难以解释,所以我将提供一个示例:
var data_base_array = [3, 3, 1, 4, 1];
var points = [];
for (var index = 0; index <= 4; index++){
points.push(point_xy_cords[data_base_array[index]][index]);
}
data_base_array
包含 1-5 之间的数字。另一个数组包含名为 point_xy_cords
的点的坐标。我想知道是否有任何方法可以用来反转这个 forloop。我无法理解它,所以一些逻辑技巧可以帮助我找到正确的方向。
例如,如果数组points
发生变化,我想相应地更改data_base_array
。 point_xy_cords 的值看起来像这样:
point_xy_cords[1-5][0-4][0-1]
因此,如果point_xy_cords[1][0]
,那么它将给出两个值的结果,(123.12, 242.11)
。
如果point_xy_cords[1][0][0]
,那么它将给出123.12
的结果。
我正在寻找类似这样的解决方案:
for (var x = 1; x <= 5; x++){
for (var y = 0; y <= 4; y++){
if (points[y][0] == point_xy_cords[x][y][0] && points[y][1] == point_xy_cords[x][y][1]){
data_base_array[y] = x;
}
}
}
上述可能的解决方案不起作用。任何方向将不胜感激。丹克。
最佳答案
我想你已经快明白了...
所以你的两个数组之间的关系是:
i1 i2, ...
data_base_array [ j1, j2, ... ]
i1 , i2 , ...
points [ point_xy_cords[j1][i1], point_xy_cords[j2][i2], ... ]
因此,iX
是索引,jX
是 data_base_array
数组上的值(其中 X
是数字)。另外,iX
是索引,point_xy_cords[jX][iX]
是 points
数组上的值。因此数组 data_base_array
和 points
的索引是相同的 (iX
)。
为了重建 data_base_array
数组,如果我们知道 points
和 point_xy_cords
数组,我们需要知道 jX
,但我们没有。因此,我们需要搜索所有可能的jX
,以找到points[iX] == point_xy_cords[jX][iX]
上可能的匹配项。
重建可以用代码完成:
// Init array
var data_base_array = [];
// For each `iX` (from 0 to 4)
for (var i = 0; i <= 4; i++){
// Init to an invalid number
data_base_array[i] = 0; // Zero is invalid
// Find correct `jX` (so search from 1 to 5)
for (var j = 1; j <= 5; j++){
// Check if `points[iX] == point_xy_cords[jX][iX]`
if (
// Javascript can't compare arrays, so compare each array item
points[i][0] == point_xy_cords[j][i][0] &&
points[i][1] == point_xy_cords[j][i][1]
){
// We found a possible `jX`
data_base_array[i] = j;
// Stop search
break;
}
}
}
但只有当您确定 point_xy_cords[i][j]
中的对在每列上都是唯一的时,这才是 100% 正确的。
关于javascript - 是否可以反转 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43037468/