更新 Javascript Array 并再次字符串化

Update Javascript Array and stringify again

本文关键字:字符串 Javascript Array 更新      更新时间:2023-09-26

所以我有这个数组

var items = ["shovel", "sword", "rope", "gun"];

我将其字符串化并放置在本地存储中

localStorage.setItem("items", JSON.stringify(items));

然后我调用这个函数,用空字符串替换传递变量的索引值。这样我就可以检查特定数组索引的值是否可用。该值将被删除,但其索引仍有待稍后检查。

function removeItem(itm) {
    var itemArray = JSON.parse(localStorage.getItem("items"));   //old array
    var index = itemArray.indexOf(itm);
    if (index > -1) {
        itemArray[index]="";  //edited new array
        localStorage.setItem("items", JSON.stringify(itemArray)); //does not store
    }
}

但是,新编辑的数组不会返回到本地存储中

对我来说

效果很好:http://jsfiddle.net/tto685z4/

var items = ["shovel", "sword", "rope", "gun"];
localStorage.setItem("items", JSON.stringify(items));
function removeItem(itm) {
    var itemArray = JSON.parse(localStorage.getItem("items"));   //old array
    var index = itemArray.indexOf(itm);
    if (index > -1) {
        itemArray[index]="";  //edited new array
        localStorage.setItem("items", JSON.stringify(itemArray)); //does not store
    }
}
removeItem('rope');
alert(localStorage.getItem('items'));

退货["shovel", "sword", "", "gun"]

您必须尝试删除不存在的项目。

如果你想删除元素,只需做一些更改:

itemArray[index]="";

更改为:

itemArray = itemArray.splice(index, 1) and you will not see this element again