简体   繁体   中英

How to filter out an element from an array in JavaScript

What am I missing here? There's an 'id' matching the condition but it still filters an array which is the same as the previous one, without removing that specific 'id'. Fan thing, if I remove the not operator it filters the only item ('id') matching the condition. Is filter working differently with not operators? I uploaded a screenshot of the console just to make it clear.

let removeFromLocalStorage = (id) =>{
    console.log(id);
    let items = accessItem();
    console.log(items);
    items = items.filter((item) =>{
        if(item.ids !== id){
            return item
        }      
    })
    console.log(items);
    localStorage.setItem('list', JSON.stringify(items));
    
}

控制台日志

From the filter method documentation available here : The filter() method creates an array filled with all array elements that pass a test

You should only return the case you want to test, in your example:

items = items.filter((item) => item.ids !== id)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM