繁体   English   中英

如何从本地存储中的数组中删除某些项目?

[英]How to delete certain item from array in localstorage?

我一直在开发一种工具来帮助人们在 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
}

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

localStorage.setItem("allCars", existingEntries)
function deleteItem(index) {
  const existingEntries = JSON.parse(localStorage.getItem("allCars"));
  existingEntries.splice(index, 1);
  localStorage.setItem("allCars", JSON.stringify(existingEntries));
}

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

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);

演示

详情见demo
注意: 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>

暂无
暂无

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

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