简体   繁体   English

从数组中删除特定项目

[英]Removing specific item from an array

I am using the following function to save items into an array in local storage. 我正在使用以下功能将项目保存到本地存储中的数组中。 Once an item has been stored I want to remove it from the array by selecting the save button again. 一旦存储了一个项目,我想通过再次选择保存按钮将其从阵列中删除。 Currently users can save the same item multiple times. 当前,用户可以多次保存同一项目。 By modifying the save button to remove the item users will have an easy way of removing items and it will prevent them from saving the same item multiple times. 通过修改保存按钮以删除项目,用户将有一种简便的方法来删除项目,这将防止他们多次保存同一项目。

$('.saveButton').click(function(){
    var film = JSON.parse(sessionStorage.getItem("film"));
    var saveFilm = JSON.parse(localStorage.getItem("save") || "[]");
    saveFilm.push(film);
    localStorage.setItem("save", JSON.stringify(saveFilm));    
});

How should I build on the function to allow me to do this? 我应该如何在该函数的基础上允许我执行此操作?

edit: 编辑:

$('.saveButton').click(function(){
    var film = JSON.parse(sessionStorage.getItem("film"));
    var saveFilm = JSON.parse(localStorage.getItem("save") || "[]");
    var arrayLength = (saveFilm.length);
    $.each(saveFilm, function(index,saveFilm){
        if(saveFilm.id===film.id){
            saveFilm.splice(saveFilm.indexOf(film), 1);
            console.log("true")
        }
        else{
            saveFilm.push(film);
            console.log("false")
        }
    localStorage.setItem("save", JSON.stringify(saveFilm));
    })
});

edit2: 编辑2:

$('.saveButton').click(function(){
var film = JSON.parse(sessionStorage.getItem("film"));
var saveFilm = JSON.parse(localStorage.getItem("save") || "[]");
var arrayLength = (saveFilm.length);
if (arrayLength>0){
    for(i=0; i<arrayLength; i++){
        if(saveFilm[i].id===film.id){
            saveFilm.splice(saveFilm.id, 1);
        }
        else{
            saveFilm.push(film);     
        }
    }
    }else{
        saveFilm.push(film);


     }
        localStorage.setItem("save", JSON.stringify(saveFilm));
});

Basically, you'll just read the value back, JSON.parse() it, remove the element, then save it again. 基本上,您只需要读回该值,即可将其JSON.parse()删除,删除该元素,然后再次保存它。

If you're just adding it to the function above, just add something like this: 如果您只是将其添加到上面的函数中,只需添加以下内容:

$('.saveButton').click(function(){
    var film = JSON.parse(sessionStorage.getItem("film"));
    var saveFilm = JSON.parse(localStorage.getItem("save") || "[]");

    if (!saveFilm.includes(film)) {
      saveFilm.push(film);
    } else {
      saveFilm.splice(saveFilm.indexOf(film), 1);
    }

    localStorage.setItem("save", JSON.stringify(saveFilm));    
});

If film is an object though, this won't work. 如果film是物体,那将行不通。 Instead, you'll need to have some kind of key you can use to find the element (such as name) which you'll instead loop through the array and find. 相反,您将需要某种可用于查找元素(例如名称)的键,而将其循环遍历数组并查找。 Once you find it (or don't find it), then the logic I shared will work again. 一旦找到(或找不到),我共享的逻辑将再次起作用。

// assuming film.name is a valid unique identifier 
function getFilmIndex(films, film) {
   const film = films.find(f => f.name === film.name);
   return film ? null : films.indexOf(film);
}

You have to be careful when splicing from front to end. 从头到尾进行拼接时必须小心。 When splicing and iterating automatically (using for loop as (var i = 0; i < arr.length; i++)) what ends up happening is if you have duplicates back-to-back then you will skip the duplicate. 当自动进行拼接和迭代时(使用for循环为(var i = 0; i <arr.length; i ++)),最终发生的事情是如果背对背有重复项,那么您将跳过重复项。

 var arr = [1, 2, 2, 3, 4], toRemove = 2; for(var i = 0; i < arr.length; i++){ if(arr[i] === toRemove) arr.splice(i, 1); } console.log(arr); 

What happens is you get rid of the first 2, move the second where that 2 was but starting looking at 3. There are 2 ways prevents this: 发生的情况是您摆脱了第一个2,将第二个移到该2所在的位置,但开始查看3。有两种方法可以防止这种情况:

1. Manually iterate i when you do not splice an element 1.不连接元素时手动迭代i

 var arr = [1, 2, 2, 3, 4], toRemove = 2; for(var i = 0; i < arr.length;){ if(arr[i] === toRemove){ arr.splice(i, 1); }else{ i++; } } console.log(arr); 

2. Itererate in reverse order (preferred way) 2.以相反的顺序进行迭代(首选方式)

 var arr = [1, 2, 2, 3, 4], toRemove = 2; for(var i = arr.length - 1; i > 0; i--){ if(arr[i] === toRemove) arr.splice(i, 1); } console.log(arr); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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