Array.filter无法正常工作

时间:2021-12-14 21:28:43

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));

1 个解决方案

#1


12  

You need to return true or false in 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()

您需要在过滤器中返回true或false以便从数组中过滤数据,返回true以保留元素,否则返回false。所以你可以使用filter()做这样的事情

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

#1


12  

You need to return true or false in 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()

您需要在过滤器中返回true或false以便从数组中过滤数据,返回true以保留元素,否则返回false。所以你可以使用filter()做这样的事情

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