1//storing array in localStorage
2var colors = ["red","blue","green"];
3localStorage.setItem("my_colors", JSON.stringify(colors)); //store colors
4var storedColors = JSON.parse(localStorage.getItem("my_colors")); //get them back
1var names = [];
2names[0] = prompt("New member name?");
3localStorage.setItem("names", JSON.stringify(names));
4
5//...
6var storedNames = JSON.parse(localStorage.getItem("names"));
1var myArray = [1,"word",23,-12,"string"];//your list of values, they can be strings or numbers
2
3//SAVING
4function save(a,b,c,d,e) {//the number of parameters you add is how many items you save
5 var itemArray = [a,b,c,d,e];//number of items here must be the same as number of parameters
6 var keyArray = ["one","two","three","four","five"];//must be same length as itemArray
7 for (var i = 0; i < keyArray.length; i++) {
8 if (typeof(itemArray[i]) === "number") {
9 itemArray[i] = "+"+itemArray[i];//leave a reminder that it was a number
10 }
11 if (typeof(itemArray[i]) !== undefined) {
12 localStorage.setItem(keyArray[i],itemArray[i]);//only add a value to the current key if it's not undefined
13 }
14 }
15}
16//to use the function (whenever you want to save):
17save.apply(this, myArray);//assuming that myArray is the array you want to set
18
19//LOADING
20function load() {
21 var list = [];
22 var keyArray = ["one","two","three","four","five"];
23 for (var i = 0; i < keyArray.length; i++) {
24 var item = localStorage.getItem(keyArray[i]);
25 if (item.charAt(0) == "+") {
26 item = parseFloat(item.substring(1));
27 }
28 list.push(item);
29 }
30 return list;
31}
32//to use the function
33myArray = load();//sets your array back to how it was when you saved it
1// our array
2var movies = ["Reservoir Dogs", "Pulp Fiction", "Jackie Brown",
3"Kill Bill", "Death Proof", "Inglourious Basterds"];
4
5// storing our array as a string
6localStorage.setItem("quentinTarantino", JSON.stringify(movies));
7
8// retrieving our data and converting it back into an array
9var retrievedData = localStorage.getItem("quentinTarantino");
10var movies2 = JSON.parse(retrievedData);
11
12//making sure it still is an array
13alert(movies2.length);