sessionStorage into array and print all values in the array

CodeName picture CodeName · Jun 28, 2016 · Viewed 17.9k times · Source

I am currently trying to store an array into sessionStorage and then retrieve the data from sessionStorage. Then, store the sessionStorage data back into an array.

var testArray = ["Shirt", "Bottom", "Shoes"];
window.sessionStorage.setItem("items", JSON.stringify(testArray));
var storedArray = JSON.parse('[' + sessionStorage.getItem("items") + ']');
var i;
for (i = 0; i < storedArray.length; i++) {
     alert(storedArray[i]);
}

Am I doing anything wrong here?

Answer

Michelangelo picture Michelangelo · Jun 28, 2016

It is already stored as an array, you don't need the brackets. What you are doing is putting the original array in a new array.

try this:

var testArray = ["Shirt", "Bottom", "Shoes"];
window.sessionStorage.setItem("items", JSON.stringify(testArray));
var storedArray = JSON.parse(sessionStorage.getItem("items"));//no brackets
var i;
for (i = 0; i < storedArray.length; i++) {
             alert(storedArray[i]);
}

https://jsfiddle.net/517x5rcg/