更新 Javascript Array 并再次字符串化
Update Javascript Array and stringify again
所以我有这个数组
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
相关文章:
- 将DOM节点值与字符串Javascript进行比较
- 到UpperCase字符串Javascript中的特定字符索引
- 替换字符串javascript中的所有特殊字符..
- 在数组中查找某些字符串(Javascript)
- 解析特定的字符串Javascript(Node.js)
- 从字符串 JavaScript 中过滤多个正则表达式
- 在字符串 JavaScript 中使用正则表达式替换
- 忽略字符串javascript中的字符
- 如何检查url是否包含多个字符串.Javascript/jquery
- 截断字符串JavaScript
- 计算字符串javascript中的某些单词
- 从'获取本月的最后一天;2015-02-23'字符串(javascript)
- 从字符串javascript中获取键值对
- 从路径字符串 - Javascript 获取所有父路径
- 在字符串Javascript中查找丢失的字母
- AngularJS:如何使所有ng模型都是字符串.JavaScript和长整数
- 将浮点转换为至少有一个小数点的字符串(javascript)
- 替换字符串 JavaScript 中的多个文本
- 检查另一个字符串 JavaScript 中一个字符串是否有任何字符的最佳方法
- 将变量的值包含在 href 字符串 javascript 中