从localStorage删除特定项目 [英] Removing specific item from localStorage
问题描述
我正在使用jQuery/JS将一些项目添加到localStorage,这一切都很好,但是在尝试删除数组中的特定项目(如果相同的项目)方面却很困难.
I'm adding some items to localStorage, using jQuery/JS, which is all fine but in trying to remove a specific item within the array (if it's the same item) is proving difficult.
在我的控制台日志(用于测试)中,似乎清除了[Object],但它没有更新密钥.也许我的等级是错误的...有什么想法吗?
In my console logs (for testing) it seems to clear the [Object] but it's not updating the key. Perhaps my hierarchy is wrong... any ideas?
//
function addToStorage(elem, name) {
localData = localStorage.getItem(name + 'Storage');
var typefaces;
if (localData == 'null' || !localData) {
typefaces = [];
} else {
typefaces = JSON.parse(localData);
}
typefaceID = elem.find('input').val();
typefaceName = elem.find('input').attr('data-name');
typefacePrice = elem.find('input').attr('data-price');
typefaceQty = 1;
$.each(typefaces, function(index, value) {
if (value !== null) {
if (value.id == typefaceID) {
if (name == 'drf') {
//console.log(index);
//console.log(typefaces);
typefaces.splice(index, 1);
//console.log(typefaces);
}
}
}
});
typefaces.push({
'id': typefaceID,
'name': typefaceName,
'price': typefacePrice,
'qty': typefaceQty
});
localStorage.setItem(name + 'Storage', JSON.stringify(typefaces));
}
//
$(document).on('click', 'summary.cart td.font', function(e) {
e.preventDefault();
addTo = $(this);
addTo.each(function() {
addToStorage(addTo, 'drf');
});
});
这是将localData添加到其中后的示例.
This is an example of the localData once it's been added to.
[
{
"id":"dr-raymond-desktop-40374",
"name":"DR-Raymond",
"format":"Desktop (OTF)",
"price":"15.00",
"qty":1
},
{
"id":"dr-raymond-webfont-39949",
"name":"DR-Raymond",
"format":"Webfont (WOFF)",
"price":"15.00",
"qty":1
}
]
推荐答案
在使用"foreach"进行迭代时,切勿在数组中添加/删除元素.相反,请尝试以下操作:
Never add/remove elements from an array while iterating over it using "foreach". Instead, try this:
for (index = typefaces.length - 1; index >= 0; index--){
value = typefaces[index];
if (value !== null) {
if (value.id == typefaceID) {
if (name == 'drf') {
typefaces.splice(index, 1);
}
}
}
});
另一种更优雅的方法是使用ES6 filter():
Another way to do this more elegantly is by using ES6 filter():
typefaces = typefaces.filter(value => !(value && value.id == typefaceID && name == "drf"));
此外,您正在将 localData
与文字字符串'null'
进行比较,这毫无意义.您的第二个条件-在这种情况下, if(!localData)
就足够了,并且可以正确处理.
Also, you are comparing localData
to the literal string 'null'
which is kind of pointless. Your second condition - if (!localData)
is enough in this case, and will handle it properly.
这篇关于从localStorage删除特定项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!