最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Arrays and Localstorage - Stack Overflow

programmeradmin0浏览0评论

I'm having a little problem here, i have an array like 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 THE ARRAY
      contador = contador +1;

  }
  if (Modernizr.localstorage) 
  {
    localStorage.setItem(localStorageKey000, pesoFecha); //STORAGE THE ARRAY
  }
}

The problem is that, when i try to load the array in local storage, i can't acces any data, all are "undefined" and i don't know why... Here is how i load the data from the array (in this case only the first objetc):

function damePrimerObjetoPesoFecha()
{
   //LOAD THE ARRAY FROM LOCAL STORAGE
   var localStorageKey000 = "objetosPesoFecha";
   var arrayDeObjetos = localStorage.getItem(localStorageKey000);

   //CHECK IN AN ALERT IF THE DATA IS OK
   alert("El primero que devuelve"+arrayDeObjetos[0].id);

   //RETURN THE FIRSTONE
   return arrayDeObjetos[0];
}

I'm having a little problem here, i have an array like 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 THE ARRAY
      contador = contador +1;

  }
  if (Modernizr.localstorage) 
  {
    localStorage.setItem(localStorageKey000, pesoFecha); //STORAGE THE ARRAY
  }
}

The problem is that, when i try to load the array in local storage, i can't acces any data, all are "undefined" and i don't know why... Here is how i load the data from the array (in this case only the first objetc):

function damePrimerObjetoPesoFecha()
{
   //LOAD THE ARRAY FROM LOCAL STORAGE
   var localStorageKey000 = "objetosPesoFecha";
   var arrayDeObjetos = localStorage.getItem(localStorageKey000);

   //CHECK IN AN ALERT IF THE DATA IS OK
   alert("El primero que devuelve"+arrayDeObjetos[0].id);

   //RETURN THE FIRSTONE
   return arrayDeObjetos[0];
}
Share Improve this question asked Jul 31, 2013 at 19:03 Alexis PolakAlexis Polak 993 silver badges11 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 2

An array can't be pushed into localStorage just like how it is. You have to use JSON.stringify on it. This line :

localStorage.setItem(localStorageKey000, pesoFecha);

must be changed to

localStorage.setItem(localStorageKey000, JSON.stringify(pesoFecha)); 

Similarly, when you're retrieving it from localStorage, you must use JSON.parse on it to convert it back to JSON. This line :

 var arrayDeObjetos = localStorage.getItem(localStorageKey000);

must be :

 var arrayDeObjetos = JSON.parse(localStorage.getItem(localStorageKey000));

Now when you access the first data, you wont get undefined.

Another alternative to this would be jStorage plugin which is wrapper around localStorage. It will take all the parsing problems from you and do it by itself if you pass an array or object to it.

Hope this helps!

localStorage only stores data as string.
You can strinify your array into JSON and save that and then parse it back when you load it

localStorage.setItem(localStorageKey000, JSON.stringify(pesoFecha)); //STORAGE THE ARRAY

var arrayDeObjetos = JSON.parse(localStorage.getItem(localStorageKey000));

LocalStorage can store strings only. You also need to remember that JSON.stringify converts date objects to string, so when deserializing via JSON.parse you need to manually create date for each object from array based on that string. Firstly:

localStorage.setItem(localStorageKey000, JSON.stringify(pesoFecha)); 

and then

 var arrayDeObjetos = JSON.parse(localStorage.getItem(localStorageKey000));
 arrayDeObjetos.forEach(function(objecto){
      objecto.fecha = new Date(objecto.fecha );
 })

localstorage can only store strings.

If you want to store arrays & objects, you should convert them to JSON.

Here's a small helper:

var LS = {
    set: function (key, val) {
        return localStorage.setItem(key, JSON.stringify(val));
    },
    get: function (key) {
        return JSON.parse( localStorage.getItem(key) );
    }
};

Use it as follows:

// Store the array:
LS.set(localStorageKey000, pesoFecha);

// Retrieve the array:
var arrayDeObjetos = LS.get(localStorageKey000);

Here's the fiddle: http://jsfiddle/KkgXU/

发布评论

评论列表(0)

  1. 暂无评论