【问题标题】:Remove range of numeric from javascript array从javascript数组中删除数字范围
【发布时间】:2017-05-30 13:26:27
【问题描述】:

我有一个 [2016,2017,2018,2019] 数组

我有一个从Value 2017到Value 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);
        }

    }
});

【问题讨论】:

  • 怎么样?使用过滤器?

标签: javascript jquery arrays scripting logic


【解决方案1】:

使用Array.prototype.filter 来实现:

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

result 包含所有匹配项的数组

【讨论】:

【解决方案2】:

使用 Array.prototype.filter 是正确的答案,但值得注意的是您没有正确使用 forEach 函数。根据Array.prototype.forEach

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

如果您想使用forEach 函数,那么您应该使用同一个数组的 2 个副本,第一个用于迭代,第二个用于删除。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-02-16
    • 2012-01-26
    • 2014-10-16
    • 2016-06-06
    • 1970-01-01
    • 2022-01-26
    • 1970-01-01
    相关资源
    最近更新 更多