user18353885
user18353885

Reputation:

How do I save all my created variables to local storage? (Javascript/HTML)

Straight to the point. I am in the process of making a game right now, I have come to the point where I want to save all my variables to the local storage.

And YES I know the good ol' way:

localStorage.setItem("var1", 5)

var1 = parseInt(localStorage.getItem("var1"))

That's all good and all, but I have WAYYY to many variables to type all that out manually, Is there a way to save all my variables to local storage with only a couple lines of code? then on refresh, set all variables back to there corresponding value in local storage

Upvotes: 0

Views: 456

Answers (1)

Oleksandr H.
Oleksandr H.

Reputation: 76

Why not instead of using many variables just use one object? Then you save it once and read it once:

let variables = {
    "var1" : 5,
    "var2" : 10
};
 
localStorage.setItem("vars", JSON.stringify(variables));
...
let variables = JSON.parse(localStorage.getItem("vars"));

Upvotes: 1

Related Questions