set array in localstorage code example
Example 1: javascript store array in localstorage
var colors = ["red","blue","green"];
localStorage.setItem("my_colors", JSON.stringify(colors));
var storedColors = JSON.parse(localStorage.getItem("my_colors"));
Example 2: localstorage javascript array
var array = [1, 2, 3];
localStorage.setItem('myArray', JSON.stringify(array));
var array = localStorage.getItem('myArray');
array = JSON.parse(array);
Example 3: set array of objects in localstorage
localStorage.setItem("savedData", JSON.stringify(objects));
objects = JSON.parse(localStorage.getItem("savedData")));
Example 4: js save and load an array of different types into localstorage
var myArray = [1,"word",23,-12,"string"];
function save(a,b,c,d,e) {
var itemArray = [a,b,c,d,e];
var keyArray = ["one","two","three","four","five"];
for (var i = 0; i < keyArray.length; i++) {
if (typeof(itemArray[i]) === "number") {
itemArray[i] = "+"+itemArray[i];
}
if (typeof(itemArray[i]) !== undefined) {
localStorage.setItem(keyArray[i],itemArray[i]);
}
}
}
save.apply(this, myArray);
function load() {
var list = [];
var keyArray = ["one","two","three","four","five"];
for (var i = 0; i < keyArray.length; i++) {
var item = localStorage.getItem(keyArray[i]);
if (item.charAt(0) == "+") {
item = parseFloat(item.substring(1));
}
list.push(item);
}
return list;
}
myArray = load();