Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 933
CodeName Avatar asked Jun 28 '16 18:06

CodeName


1 Answers

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/

like image 112
Michelangelo Avatar answered Nov 14 '22 23:11

Michelangelo