Search code examples
javascripthtmlfor-loopsessionstorage

How to improve this sessionstorage naming system/for loop?


I have a shopping cart that is using sessionstorage to store items. 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. I then use this for loop to read values:

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. 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? I did a quick fix by having my for loop check up to 50, but this just seems sloppy and a hog of resources...


Solution

  • 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. 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. 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.