Search code examples
javascriptarraysjsonsession-storage

sessionStorage into array and print all values in the array


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?


Solution

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