Question

I have localstorage working to where I can save inputs and push them to a list. Now I would like to save the list in localstorage because when I reload the list resets because of var fav = new Array(); is defined at the start in this jsFiddle. How can I work around this?

Thanks, Ben

Était-ce utile?

La solution

It's realy easy, you just need to use JSON data to save it :

// Save
var datas = ["1", "2", "3"];
localStorage["datas"] = JSON.stringify(datas);

// Retrieve
var stored_datas = JSON.parse(localStorage["datas"]);

Autres conseils

The reason some people are getting undefined is because of JS.. for example, if you run [][0] it is undefined. The answer from Andy/Arthur above initially worked locally for me but ended up breaking in production. I fixed it by using the methods/syntax defined in the MDN docs using it as so...

to set a value:

const myArray = []
localStorage.setItem('myArray', JSON.stringify(myArray))

to get a value:

const myArrayFromLocalStorage = localStorage.getItem('myArray')
if (myArrayFromLocalStorage && myArrayFromLocalStorage.length) {
const myArray = JSON.parse(myArrayFromLocalStorage)
}

to clear a value:

localStorage.removeItem('myArray')

This is simple to do with localDataStorage, where you can transparently set/get any of the following "types": Array, Boolean, Date, Float, Integer, Null, Object or String.

[DISCLAIMER] I am the author of the utility [/DISCLAIMER]

Examples:

localDataStorage.set( 'key1', 'Belgian' );
localDataStorage.set( 'key2', 1200.0047 );
localDataStorage.set( 'key3', true );
localDataStorage.set( 'key4', { 'RSK' : [1,'3',5,'7',9] } );
localDataStorage.set( 'key5', null );

localDataStorage.get( 'key1' );   -->   'Belgian'
localDataStorage.get( 'key2' );   -->   1200.0047
localDataStorage.get( 'key3' );   -->   true
localDataStorage.get( 'key4' );   -->   Object {RSK: Array(5)}
localDataStorage.get( 'key5' );   -->   null

As you can see, the primitive values are respected. In your case, we would do this:

>localDataStorage.set( 'datas', ["1", "2", "3"] );

Note that we didn't need to do any stringification to our key value. You can specify it plainly and clearly. Now, when we retrieve it...

>localDataStorage.get( 'datas' ) -->

... we will get:

>(3) ["1", "2", "3"] 

exactly what we started with, without having to convert anything.

If you want to prevent your variable from being reset try this, if you want to reload page and keep old value this is not gonna help thought.

  if (typeof fav === 'undefined'){
        var fav = new Array();}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top