Storing variables in HTML5 localStorage

2019-09-20 00:51发布

问题:

I'm currently in development of a minesweeper game and I want to store the value of a 'noWins' variable into local storage once the game is won (I have a boolean called wonGame which is set to true when the game is won).

How can I do this?

回答1:

To store data in localStorage, you use the setItem() function. This function takes two parameters, the item key and a value.

if(wonGame == true){
  localStorage.setItem('noWins', 'value');
}

In response to your comment,

local storage stores values as strings, therefore the value has to be converted to a number using parseInt. The first value for noWins would be set to 0

so the new code should be

//set the initial value of noWins to 0
localStorage.setItem('noWins' , 0)
if (wonGame === true){
var winning = parseInt(localstorage.getItem("noWins");
//increment value
localStorage.setItem("winning", winning++)
}

Note that "winning" is just a variable I created