首页 > 解决方案 > 如何从 localStorage 数组中删除项目?我有

问题描述

我有一个存储在 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?

标签: javascript

解决方案


localStorage是一个简单的基于字符串的存储。为了删除一个项目,你需要阅读它(就像你做的那样),删除它(就像你做的那样)并再次存储它:

localStorage.setItem('cars', JSON.stringify(modifiedCars));

推荐阅读