问题
I'm currently making a Mario-esque game with Javascript, or more precisely, CraftyJS.
I've looked here as reference, and understand how to save values inputed by the user. But what I want to accomplish is to save certain booleans(is that what they are called?) automatically, or when the player presses a save button or something.
For example, I have a dungeon called dungeon1, and I create a variable to represent whether or not the dungeon has been completed.
It's var dungeon1 = false;
by default.
But when the player completes dungeon1, it changes to var dungeon1 = true;
,
resulting in new additions to the world map, such as a portal to dungeon2(this is working fine).
What I want to save is this var dungeon1 = true;
statement, so that when the user opens the game again, the dungeons completed will be loaded and the corresponding unlocks will be shown correctly. How would I do so?
Is there a way to say, make a save management file called save.js
, then store booleans such as the one above once they become true
?
回答1:
You would just store the string version of the boolean that you want.
So store "true" and "false", and instead of checking just like if(variable) you'd have to check in the form of if(variable === "true"). Its a little derpy but you can see how it doesn't really add more complexity to your code.
If that type of if checking just offends your sensibilities, then in the code where you "get" it from the localStorage you could then recast it to a boolean.
var bool = (localStorage.getItem("myItem") === "true")
PS. you can setItem with booleans... it will just cast them to strings :D because most things it calls toString() on to store them if they aren't already strings.
So you can do:
enter code here
localStorage.setItem("myItem", true)
来源:https://stackoverflow.com/questions/20533634/workaround-for-not-being-able-to-save-booleans-with-html5-web-storage