【问题标题】:How to delete certain item from array in localstorage?如何从本地存储中的数组中删除某些项目?
【发布时间】:2023-03-10 08:34:02
【问题描述】:

我一直在开发一种工具来帮助人们在 GTA 中跟踪他们的汽车,但我不知道如何删除它们。

我尝试了多种方法,但无法正常工作。

这是我的密码笔https://codepen.io/Tristangre97/pen/dyoyOKw?editors=1010

function deleteItem(index) {
  var existingEntries = JSON.parse(localStorage.getItem("allCars"));
  existingEntries.splice(0, index); // delete item at index
}

【问题讨论】:

  • 请提供minimal reproducible example。一个 codepen 的链接是不够的。
  • 从数组中删除项目后,您应该再次调用localstorage.setItem 以更新本地存储

标签: javascript arrays local-storage


【解决方案1】:

Splice 不会更新本地存储,相反,一旦您删除了需要将新数组写回本地存储的项目:

localStorage.setItem("allCars", existingEntries)

【讨论】:

    【解决方案2】:
    function deleteItem(index) {
      const existingEntries = JSON.parse(localStorage.getItem("allCars"));
      existingEntries.splice(index, 1);
      localStorage.setItem("allCars", JSON.stringify(existingEntries));
    }
    

    splice 中的第一个参数是索引,第二个参数是长度。 此外,您应该将新数组保存到 localStorage。

    【讨论】:

    • 这有帮助,谢谢。不过,您确实不小心添加了逗号而不是句号。
    【解决方案3】:

    CodePen 提供的工作...所以我假设它已得到纠正,因为问题是.splice() Array 方法的 2 个参数的位置不正确:

    原创

    /*
    1st parameter is the index position of where within the array to start
    2nd parameter is the quantity of array elements to remove
    So this would always start at the beginning of the array and nth amount of elements
    */
    existingEntries.splice(0, index);
    

    正确

    /*
    This will start at the specified index position and remove just that element
    */
     existingEntries.splice(index, 1);
    

    演示

    详细信息在演示中注释
    注意: SO Stack Snippets 会阻止 Web Storage API,因此要查看正常运行的演示,请参阅此 CodePen

    // Reference the <form>
    const list = document.forms.gtaList;
    
    /*
    Utility functions to get/set/show localStorage data
    lsGet() and lsSet() are self-explanatory
    the data will be either an array of objects or an empty array
    viewList() renders a <button> for each entry of the data
    */
    const lsGet = key => JSON.parse(localStorage.getItem(key)) || [];
    const lsSet = (key, value) => localStorage.setItem(key, JSON.stringify(value));
    
    const viewList = data => {
      const display = list.elements.display;
      display.value = "";
      data.forEach((entry, index) => {
        display.insertAdjacentHTML(
          "beforeend",
          `<button type='button' data-idx='${index}'>
             ${entry.address} 
             --==-- 
             ${entry.car}
           </button><br>`
        );
      });
    };
    // Initial display of data if any in localStorage
    viewList(lsGet("gtaData"));
    
    // Register the click event to the <form>
    list.onclick = autoList;
    
    // Pass the event object (ie e)
    function autoList(e) {
      // Reference all form controls of <form> (ex. input, button, select, etc)
      const gta = this.elements;
      // Get current value of <select> and <input>
      const address = gta.garage.value;
      const car = gta.auto.value;
      // Define empty object declare data
      let entry = {};
      let data;
    
      /*
      if the clicked tag (ie e.target) is a <button>...
      and if clicked tag id is '#add'...
      Get data from localStorage
      Assign the values of <select> and <input> to the entry object
      Add entry object to data array
      */
      /*
      ...or if the clicked tag has [data-idx] attribute...
      Get the [data-idx] value and convert it into a real Number
      Next remove() the clicked <button> from the DOM
      Get data from localStorage and splice() the object at the index
      position designated by the clicked <button> [data-idx] Number
      */
      /*
      Display data as a group of <button>s
      Finally set data to localStorage
      */
      if (e.target.tagName === "BUTTON") {
        if (e.target.id === "add") {
          data = lsGet("gtaData");
          entry.address = address;
          entry.car = car;
          data.push(entry);
        }
        if (e.target.hasAttribute('data-idx')) {
          let idx = Number(e.target.dataset.idx);
          e.target.remove();
          data = lsGet("gtaData");
          data.splice(idx, 1);
        }
        viewList(data);
        lsSet("gtaData", data);
      }
    }
    :root,
    body {
      width: 100%;
      height: 100%;
      margin: 0;
      padding: 0;
      font: 700 3vw/1.2 Consolas;
    }
    
    form {
      width: 90vw;
      margin: 10vh auto;
    }
    
    input,
    select,
    button {
      display: inline-block;
      padding: 2px 5px;
      font: inherit;
    }
    <form id="gtaList">
      <select id="garage">
        <option value="" selected>Select Location</option>
        <option value="Little Bighorn Ave">Little Bighorn Ave</option>
        <option value="Unit 124 Popular St">Unit 124 Popular St</option>
        <option value="1 Strawberry Ave">1 Strawberry Ave</option>
        <option value="142 Paleto Blvd">142 Paleto Blvd</option>
      </select>
      <input id="auto" placeholder="Mustang">
    
      <button id="add" type="button">Add</button>
      <fieldset>
        <legend>Click to Remove</legend>
        <output id="display"></output>
      </fieldset>
    </form>

    【讨论】:

      猜你喜欢
      • 2021-09-02
      • 2016-12-09
      • 2019-11-26
      • 1970-01-01
      • 1970-01-01
      • 2018-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多