简体   繁体   中英

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

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"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM