Home > database >  How to use localstorage in js for making quiz website
How to use localstorage in js for making quiz website

Time:11-09

I am trying to make an quiz website, and need help to store points inside localstorage in js. I have already put questions inside an object array in js.

CodePudding user response:

set item to localstorege To store points

localStorage.setItem('points', Your object with user Name and points);

To get your data from localstorage

const points = localStorage.getItem('points');

CodePudding user response:

If you store more than one number in the localStorage you have to consider something else. localStorage does not store any objects. For this reason, you must serialise objects before storing them.

const string = JSON.stringify( {score: 99, player: 'X'} ) 
// output: "{\"score\":99,\"player\":\"X\"}"
const json = JSON.parse( "{\"score\":99,\"player\":\"X\"}" ) 
// output: {score: 99, player: 'X'}

console.log('STRING',typeof string, string)
console.log('JSON',typeof json, json)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

After then you can store the value by Key to the localStorage:

localStorage.setItem('stats', string);

And to get them:

const stats = localStorage.getItem('stats');

  • Related