save array in localstorage code example

Example 1: javascript store array in localstorage

//storing array in localStorage
var colors = ["red","blue","green"];
localStorage.setItem("my_colors", JSON.stringify(colors)); //store colors
var storedColors = JSON.parse(localStorage.getItem("my_colors")); //get them back

Example 2: localstorage save array

var names = [];
names[0] = prompt("New member name?");
localStorage.setItem("names", JSON.stringify(names));

//...
var storedNames = JSON.parse(localStorage.getItem("names"));

Example 3: js save and load an array of different types into localstorage

var myArray = [1,"word",23,-12,"string"];//your list of values, they can be strings or numbers

//SAVING
function save(a,b,c,d,e) {//the number of parameters you add is how many items you save
  	var itemArray = [a,b,c,d,e];//number of items here must be the same as number of parameters
    var keyArray = ["one","two","three","four","five"];//must be same length as itemArray
    for (var i = 0; i < keyArray.length; i++) {
      	if (typeof(itemArray[i]) === "number") {
          	itemArray[i] = "+"+itemArray[i];//leave a reminder that it was a number
        }
        if (typeof(itemArray[i]) !== undefined) {
          	localStorage.setItem(keyArray[i],itemArray[i]);//only add a value to the current key if it's not undefined
        }   
    }
}
//to use the function (whenever you want to save):
save.apply(this, myArray);//assuming that myArray is the array you want to set

//LOADING
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;
}
//to use the function
myArray = load();//sets your array back to how it was when you saved it