0

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

Jordan Carter
  • 1,276
  • 3
  • 19
  • 43
  • 1
    This might be useful for you: http://stackoverflow.com/questions/3357553/how-to-store-an-array-in-localstorage – Evan Trimboli Apr 18 '16 at 00:56
  • @EvanTrimboli Thank you, this is useful, but unfortunately it might take a while to convert my way to a method with JSON, and I am running out of time. Maybe next time I'll do a solution like that. – Jordan Carter Apr 18 '16 at 01:05

1 Answers1

1

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.

regulus
  • 1,572
  • 12
  • 18
  • I understand serializing with JSON and giving it a unique key...but I don't understand "a unique key to your script". Is there a way to specifically map sessionStorage to certain script files? – Jordan Carter Apr 18 '16 at 03:08
  • What I meant was to have a key that will not collide with anything easily like `sessionStorage['__productName_Cart'] = ...`. There's no such thing to specifically map a key to certain script files. Every script file loaded as part of a page, can see every key in the session storage of that page. – regulus Apr 18 '16 at 04:39