简体   繁体   English

如何改进此会话存储命名系统/ for循环?

[英]How to improve this sessionstorage naming system/for loop?

I have a shopping cart that is using sessionstorage to store items. 我有一个使用sessionstorage存储项目的购物车。 When the user clicks "add to cart", it stores a new object with a key equal to the clickcount and a value equal to the item name. 当用户单击“添加到购物车”时,它将存储一个新对象,该对象的键等于clickcount,值等于项目名称。 I then use this for loop to read values: 然后,我使用此for循环读取值:

for (var i = 0; i < sessionStorage.length -1; i++) {
if( sessionStorage.getItem(i + 1) != null ) {
...
"<span class='item'>" +  sessionStorage.getItem(i + 1) + "</span>" +

Here's the issue. 这是问题。 Say I delete item 3 of 5 from my cart. 假设我从购物车中删除了5之3。 If I add another item, it will be called "6", but my items will be 1, 2, 4, 5, 6. My for loop will only recognize items 1, 2, 4 and 5. How do I recognize item 6? 如果添加另一个项目,它将被称为“ 6”,但是我的项目将是1、2、4、5、6。我的for循环将只能识别项目1、2、4和5。我如何识别项目6 ? I did a quick fix by having my for loop check up to 50, but this just seems sloppy and a hog of resources... 我通过让我的for循环检查多达50个来进行快速修复,但这似乎草率和大量的资源...

Well technically a for each loop would solve your problem; 从技术上讲,每个循环都可以解决您的问题;

for (var e in sessionStorage) {
    document.write(e + '=>' + sessionStorage[e]);
}

However does not matter how you access your elements, using sessionStorage this way is a poor design choice. 但是,无论您如何访问元素都没有关系,以这种方式使用sessionStorage是一个糟糕的设计选择。 First of all since sessionStorage is a shared resource across the different scripts in the same page, any other script (a library you might use for example) might add something to sessionStorage, and your script gets messed up. 首先,由于sessionStorage是同一页面中不同脚本之间的共享资源,因此任何其他脚本(例如,您可能使用的库)都可能向sessionStorage添加一些内容,从而使脚本混乱。 Encapsulation of your data, like serializing it with JSON and putting under sessionStorage with a unique key to your script will help you more in long term. 数据的封装(例如,使用JSON进行序列化以及使用脚本的唯一密钥将sessionStorage置于下面)将在长期内为您提供更多帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM