2017-05-30 117 views
0

我[2016,2017,2018,2019]删除范围

的阵列我有一个范围fromValue 2017 toValue 2017

因此所得阵列应采用[2017]由于我需要删除fromValue和toValue之间的任何范围。

我已经写了下面的代码这是只有消除2016和2018,但不是2019年

哪些错误我在做什么,有没有什么办法尤为明显要做到这一点?

gNodeIDs.forEach(function (item) {    
    alert("Before if" + item); 
    if (item >= fromValue) { 
     if (item <= toValue) {       
     } 
     else 
     { 
      alert("removing" + item); 
      var index = test.indexOf(item); 
      if (index >= 0) { 
       test.splice(index, 1); 
      } 
     } 
    } 
    else { 
     alert("removing" + item); 
     var index = test.indexOf(item); 
     if (index >= 0) { 
      test.splice(index, 1); 
     } 

    } 
}); 
+0

怎么样?使用过滤器? – SmartestVEGA

回答

2

使用Array.prototype.filter来实现这一目标:

var result = gNodeIDs.filter(function(item) { return item >= fromValue && item <= toValue }); 

result数组包含所有匹配的项目

+1

可能不是问题,但值得一提的是这是在JavaScript 1.6中添加的。但是,如果您担心它有一个polyfill https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter?v=control – disrvptor

+0

感谢它的工作! ! – SmartestVEGA

+0

@SmartestVEGA很高兴帮助,请不要忘记接受答案;) – hmnzr

1

使用Array.prototype.filter是正确的答案,但值得注意你不使用forEach功能正常。根据Array.prototype.forEach

forEach()处理的元素范围在第一次调用回调之前设置。调用forEach()之后追加到数组的元素将不会被回调访问。如果数组中现有元素的值发生更改,则传递给回调的值将是forEach()访问它们时的值;被访问之前被删除的元素不会被访问。如果已经访问的元素在迭代过程中被移除(例如使用shift()),则后面的元素将被跳过 - 参见下面的示例。

如果你想使用forEach功能,那么你应该使用相同的阵列的2份,先进行迭代和第二去除。