The localStorage does not store objects. If you put:
var miarray = [1,2,3];
localStorage.setItem('primer_array', miarray);
Implicitly happens
localStorage.setItem('primer_array', miarray.toString());
That stores the string 1,2,3
For the same reason, it is correct to insert it using JSON.stringify
as samples in your second attempt:
localStorage.setItem(x2i,JSON.stringify(arrayX2));
So to get it back "rehydrated", you have to retrieve it as
var array_guardado = JSON.parse(localStorage.getItem(x21));
On the other hand, in your logic you say that the element you want to store is defined in the snippet
var x2=x1+c;
var x2i=x2.toFixed(2);
var y2=y1+ci;
var y2i=y2.toFixed(2);//52.23
var arrayX2=new Array(); // arrayX2 = []
arrayX2.push(y2i); // arrayX2 = ["53.23"]
var arrayX2=new Array(); // arrayX2 = []
arrayX2.push(y2i); // arrayX2 = ["53.23"]
What are the last two lines for?
Why do you redefine arrayX2
as an empty array? Redefining an already declared variable is an antipattern. Think:
var x = 'hola';
console.log(x);
// imprime 'hola';
var x;
console.log(x);
// sigue imprimiento 'hola' cuando debiera imprimir 'undefined'
Will not you want the final array to contain x2i
e y2i
Finally, it is not recommended to use the Array constructor new Array()
but the literal []
to declare a new array.
Think that
var miarray = []
when interpreted in the browser engine, call ARRAY_INIT
.
Whereas var miarray = new Array()
calls new
(constructor) Array
(identifier) and then goes through the chain of prototypes going up the stack until reaching window.Array
, and on that prototype calls the method apply
.
This happens because on the way you could have added methods to the prototype Array
(it's a bad idea, but it's done) or worse, having overwritten the constructor for example:
Array = function() {
this.nombre = 'array';
};
That would generate that
var miaarray = new Array();
Out an object with property nombre
and without methods like push
, shift
, unshift
, pop
, etc. You would have destroyed the constructor. And yet, after doing that
var miarray = [];
It would remain intact and functioning.