gpt4 book ai didi

javascript - 荒谬的 JavaScript 错误 : have to call a function multiple times for it to behave correctly

转载 作者:行者123 更新时间:2023-12-03 23:23:27 25 4
gpt4 key购买 nike

我毫不怀疑我自己的白痴对此负责。我不是程序员,而是科学家,而且我通常只是对某些东西进行破解,直到它起作用为止,这就是我最终遇到这些奇怪错误的原因。基本上,我们将不胜感激任何帮助。

好的,所以我的功能是这样的:

function discardDuplicates(threshold) {
for (var m = 0; m < xCo2.length; m++){
var testX = xCo2[m];
var testY = yCo2[m];
for (var n = 0; n < xCo2.length; n++){
if (m != n) {
if ((Math.abs(xCo2[n] - testX) < threshold)
&& (Math.abs(yCo2[n] - testY) < threshold)
&& deltas[m] > deltas[n]){

xCo2.splice(n,1);
yCo2.splice(n,1);
deltas.splice(n,1);
}
}
}
}
}

我正在检测坐标 (x,y) 存储在 xCo2 和 yCo2 数组中的特征,每个坐标也有一个称为“delta”的属性。我想检查一下我是否在基本相同的地方确定了几个特征——如果我有,它们可能是重复的,所以我从列表中删除除了具有最高 delta 的那个之外的所有特征。

对,基本上,这是行不通的!

目前我必须这样做:

//ugly hack 
var oldLength = 0;
var newLength = 1;
while (oldLength != newLength) {
oldLength = xCo2.length;
discardDuplicates(10);
newLength = xCo2.length;
}

因为第一次调用该函数时它不会删除任何重复项。第二次它删除了其中的大部分。第三次它通常都有它们......所以我只是继续调用它直到它停止删除重复项。该功能确实有效;它正在删除正确的点。

我问这个问题的原因是,同样的错误现在已经第二次发生,第二个函数,这次试图删除任何增量值太​​低的坐标。

启蒙将被感激地接受!

最佳答案

在数组上调用 splice 将删除一个条目并将下一个条目移动到该位置,这是非常常见的错误。

让我们来看看:

xCo2 = [1, 2, 3, 4, 5];
n = 0;

xCo2.splice(n, 1); // n = 0, removed 1
>> [2, 3, 4, 5];
n ++;

xCo2.splice(n, 1); // n = 1, removed 3
>> [2, 4, 5];
n++;

看到问题了吗?您正在跳过条目,您需要做的是每次从数组中删除条目时减少 n。由于您总是删除 1 个条目,因此在拼接数组后需要将 n 减少一次。

if ((Math.abs(xCo2[n] - testX) < threshold)
&& (Math.abs(yCo2[n] - testY) < threshold) && deltas[m] > deltas[n] ){

xCo2.splice(n,1);
yCo2.splice(n,1);
deltas.splice(n,1);
n--;
}

PS:一些空格会大大提高代码的可读性。

关于javascript - 荒谬的 JavaScript 错误 : have to call a function multiple times for it to behave correctly,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4239348/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com