Javascript 如何从 sessionStorage (AngularJs) 中删除单个对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27269168/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to remove single object from the sessionStorage (AngularJs)
提问by DIGAMBAR TOPE
I add list to sessionStorage like:
我将列表添加到 sessionStorage 中,例如:
var item = new cartItem(product.id, product.name, product.price, qty);
orderItem.push(item);
sessionStorage.setItem('addedProductsList', JSON.stringify(orderItem));
var retrieveArray= JSON.parse(sessionStorage.addedProductsList);
and its working fine, now i want to remove a single object from this list by productId.
并且它工作正常,现在我想通过 productId 从此列表中删除一个对象。
回答by Artyom Pranovich
Please, see the following article: http://www.nczonline.net/blog/2009/07/21/introduction-to-sessionstorage/
请参阅以下文章:http: //www.nczonline.net/blog/2009/07/21/introduction-to-sessionstorage/
If you want to remove specify key/value pair from session storage, you need smth like this:
如果你想从会话存储中删除指定的键/值对,你需要像这样:
sessionStorage.removeItem(key)
For your case:
对于您的情况:
var retrieveArray= JSON.parse(sessionStorage.addedProductsList);
for (i=0; i<retrieveArray.length; i++){
if (retrieveArray[i].id == "Your ProductId") {
retrieveArray.splice(i,1);
}
}
sessionStorage.addedProductsList = retrieveArray;
Additionally, proper implementations allow you to read, write, and remove values from sessionStorage as if it were a regular object. For example:
此外,适当的实现允许您从 sessionStorage 中读取、写入和删除值,就好像它是一个常规对象一样。例如:
//save a value
sessionStorage.name = "Name";
//retrieve item
var name = sessionStorage.name;
//remove the key
delete sessionStorage.name;

