我有一个数组,我用范围滑块进行过滤。如果特定所选参数的值在用户的最小(tMin)和最大(tMax)值范围内,则将其添加到新数组(myNewArray)并以我需要的方式重新格式化。超出范围的任何内容都不会添加到此新阵列中。这部分工作得很好。
我似乎无法工作的是我有一个单独的数组(myOtherArray),其格式与myArray完全相同,但不是重新格式化我只需删除该行,如果它没有&#39 ; t落在范围内。 myOtherArray应该具有与myNewArray相同的值和行数,但它们的格式都不同。我在这里做错了什么?
myArray.map(function (dataPoint, index) {
if (index > 0) {
dataPoint.map(function (value, column) {
// this first part works fine
if ( dataPoint[paramToFilter] >= tMin && dataPoint[paramToFilter] <= tMax ) {
myNewArray[column] ? myNewArray[column].push(+value) : myNewArray[column] = [+value]
}
// this is what I cannot get to work
if ( dataPoint[paramToFilter] < tMin || dataPoint[paramToFilter] > tMax ) {
myOtherArray.splice(index, 1);
}
})
}
})
谢谢!!
答案 0 :(得分:2)
问题在于,myOtherArray
的值与myArray
中的myOtherArray.splice(index, 1)
相同,而myArray.map(...)
的价值与myOtherArray.splice(index, 1);
不同。
以下是一个显示问题的小例子:http://jsbin.com/wipozu/1/edit?js,console
为了避免这个问题,您可以简单地&#34;标记&#34;那些要删除的数组项而不是立即删除它。完成所有检查后(undefined
之后),您可以删除所有这些&#34;标记为&#34;项目
因此,您可以使用myOtherArray[index] = undefined;
(或任何其他值)替换项目,而不是调用undefined
- &gt; for (var i = 0; i < myOtherArray.length; i++)
{
if (myOtherArray[i] === undefined)
{
myOtherArray.splice(i, 1);
// correct the index to start again on the same position because all
// followings item has moved one index to the left in the array
i--;
}
}
然后运行以下命令以删除所有myArray.map(function (dataPoint, index) {
if (index > 0) {
dataPoint.map(function (value, column) {
if ( dataPoint[paramToFilter] >= tMin && dataPoint[paramToFilter] <= tMax ) {
myNewArray[column] ? myNewArray[column].push(+value) : myNewArray[column] = [+value]
}
if ( dataPoint[paramToFilter] < tMin || dataPoint[paramToFilter] > tMax ) {
myOtherArray[index] = undefined; // should be removed afterwards
}
})
}
})
// remove all items that have been marked
for (var i = 0; i < myOtherArray.length; i++)
{
if (myOtherArray[i] === undefined)
{
myOtherArray.splice(i, 1);
// correct the index to start again on the same position because all
// followings item has moved one index to the left in the array
i--;
}
}
项。
{{1}}
以前的相同示例,但使用我的解决方案:http://jsbin.com/wipozu/2/edit?js,console
因此,您的代码如下所示:
{{1}}
答案 1 :(得分:0)
问题是当你拼出一个元素时,所有下列元素的索引都会向下移动。因此,myArray
和myOtherArray
中的索引不再同步,当您稍后执行myOtherArray.splice(index, 1)
时,您将删除错误的元素。
最简单的解决方案是从高到低迭代而不是从低到高:
for (var index = myArray.length-1; index > 0; index--) {
...
}