sessionStorage into array and print all values in the array

23,857

Solution 1

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/

Solution 2

You don't need to wrap the array with []. sessionStorage.getItem("items") returns the JSON stringified array, you are wrapping the array with another array. Your problem is the alert function that converts the array into a string (just like joined array elements by calling the Array.prototype.join method), this is because alert can only show strings. This probably makes you think that there is no array. Use console.log for debugging.

Share:
23,857
CodeName
Author by

CodeName

Updated on July 17, 2022

Comments

  • CodeName
    CodeName almost 2 years

    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?