2015-09-07 19 views
7

Ho un array e voglio rimuovere un record da esso ho utilizzato Array.filter() ma restituisce lo stesso array così com'è.Array.filter non funziona correttamente

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

il ritorno dalla funzione nella Array.filter dovrebbe essere vero o falso, fedele a "mantenere" l'elemento dell'array di uscita, false per "saltare" it - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter –

risposta

12

È necessario tornare true o false filtro al fine di filtrare i dati da un array, restituire TRUE per mantenere l'elemento, false altrimenti. Così si può fare qualcosa di simile utilizzando filter()

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