javascript - Arrays and Localstorage -
i'm having little problem here, have array this:
function crearobjetos() { var palabrapeso = "peso"; var palabrafecha = "fecha"; var localstoragekey000 = "objetospesofecha"; var contador = 0; var pesofecha = new array(); //the array while(contador < 365) { var nuevoobjeto = new object; var fechaactual = new date(); nuevoobjeto.peso = 0; nuevoobjeto.fecha = fechaactual; nuevoobjeto.id = contador; pesofecha[contador] = nuevoobjeto; //save objects in array contador = contador +1; } if (modernizr.localstorage) { localstorage.setitem(localstoragekey000, pesofecha); //storage array } }
the problem that, when try load array in local storage, can't acces data, "undefined" , don't know why... here how load data array (in case first objetc):
function dameprimerobjetopesofecha() { //load array local storage var localstoragekey000 = "objetospesofecha"; var arraydeobjetos = localstorage.getitem(localstoragekey000); //check in alert if data ok alert("el primero que devuelve"+arraydeobjetos[0].id); //return firstone return arraydeobjetos[0]; }
an array can't pushed localstorage
how is. have use json.stringify
on it. line :
localstorage.setitem(localstoragekey000, pesofecha);
must changed to
localstorage.setitem(localstoragekey000, json.stringify(pesofecha));
similarly, when you're retrieving localstorage
, must use json.parse
on convert json. line :
var arraydeobjetos = localstorage.getitem(localstoragekey000);
must :
var arraydeobjetos = json.parse(localstorage.getitem(localstoragekey000));
now when access first data, wont undefined
.
another alternative jstorage
plugin wrapper around localstorage
. take parsing problems , if pass array or object it.
hope helps!
Comments
Post a Comment