【问题标题】:Delete specific string from Local Storage array从本地存储阵列中删除特定字符串
【发布时间】:2020-06-08 06:28:59
【问题描述】:

我有这个代码

function deleteElement() {
        const myArray = map(listItems, getText);
        var elementToDelete =document.getElementById('deleteElement').value;
        const index = myArray.findIndex((item) => item.includes(elementToDelete));

            if (index > -1) {
            // delete and update local storage
            console.log("found element and index ", index);
            let moment = localStorage.getItem('pelis_guardades');
            let deleted = moment.splice(index, 1);
            localStorage.setItem('pelis_guardades', JSON.stringify(deleted))
            console.log(deleted);
            }
    }


我已经找到要删除的数组元素的索引,一切都很好,但现在我想“更新”本地存储以从索引中删除该项目。

我可以删除加载到本地存储中的数组上的特定值。称为 myArray。

const myArray = map(listItems, getText);

myArray 包含“原始字符串数据”,然后通过以下方式将其放入本地存储中,

localStorage.setItem('things',JSON.stringify(myArray));

如何从本地存储中删除?

我试过了,本地存储上的拼接方法不行!!

谢谢!

【问题讨论】:

    标签: javascript html arrays local-storage


    【解决方案1】:

    尝试将 moment 变量解析为 JSON 使用

    编辑

    function deleteElement() {
        const myArray = map(listItems, getText);
        var elementToDelete =document.getElementById('deleteElement').value;
        const index = myArray.findIndex((item) => item.includes(elementToDelete));
    
            if (index > -1) {
            // delete and update local storage
            console.log("found element and index ", index);
            let moment = localStorage.getItem('pelis_guardades');
            //try to add this code
            let moment_parse = JSON.parse(moment);
            let deleted = moment_parse.splice(index, 1);//edit
            localStorage.setItem('pelis_guardades', JSON.stringify(deleted))
            console.log(deleted);
            }
    

    在拼接之前矩变量

    【讨论】:

      【解决方案2】:

      问题是您在使用Array.splice 时犯了一个错误。 这个方法改变给定的数组。 您不需要splice 操作的结果。相反,您必须将数组作为新值传递以更新本地存储。

      // 1. read value
      const moment = JSON.parse(localStorage.getItem('pelis_guardades'))
      
      // 2. mutate given array by removing one element from index.
      moment.splice(index, 1);
      
      // 3. write value
      localStorage.setItem('pelis_guardades', JSON.stringify(moment))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-12-03
        • 1970-01-01
        • 2018-07-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-02-04
        相关资源
        最近更新 更多