我有一个存储在localStorage中的数组。如何删除数组的值,然后再次将其保存在localStorage中?
var cars = ["Saab", "Volvo", "BMW"];
localStorage.setItem("cars", JSON.stringify(cars));
let modifiedCars = JSON.parse(localStorage.getItem("cars")).splice(0, 1)
// How do I remove cars[0] from the array and store it back into localStorage?
答案 0 :(得分:1)
localStorage
是一个简单的基于字符串的存储。为了删除项目,您需要阅读它(就像以前一样),将其删除(就像您一样)并再次存储:
localStorage.setItem('cars', JSON.stringify(modifiedCars));
答案 1 :(得分:0)
我更喜欢使用.filter()
删除元素;
var cars = ["Saab", "Volvo", "BMW"];
localStorage.setItem("cars", JSON.stringify(cars));
let modifiedCars = JSON.parse(localStorage.getItem("cars")).filter(el => el!= "Saab")
localStorage.setItem("cars", JSON.stringify(modifiedCars ));