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?
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]);
}
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.