Javascript Array.filter 工作不正常

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32437396/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 08:02:57  来源:igfitidea点击:

Array.filter is not working properly

javascriptjqueryarrays

提问by Pranav C Balan

I have an array and i want to remove a record from it i have use Array.filter()but its return same array as it is.

我有一个数组,我想从中删除我使用过的记录,Array.filter()但它返回的数组与原来的数组相同。

My Code:

我的代码:

var url = window.location.pathname,
    orderId = url.split('/').slice(-2)[0];
var Cart = JSON.parse(localStorage.getItem('Cart'));
newCart=Cart.filter(function(item) {
    if (parseInt(item.orderId) == parseInt(orderId)) {
        return {};
    }
    else
    {
        return item;
    }
});
localStorage.setItem('Cart',JSON.stringify(newCart));

回答by Pranav C Balan

You need to return trueor falsein filter in order to filter data from an array, Return true to keep the element, false otherwise. So you can do something like this using filter()

您需要 returntruefalsein filter 以从数组中过滤数据,返回 true 以保留元素,否则返回 false。所以你可以使用filter()

newCart = Cart.filter(function(item) {
    return parseInt(item.orderId, 10) != parseInt(orderId, 10);
});