Created
January 27, 2021 12:33
-
-
Save ross-u/cd2d5da46106ab7d349150b196ff4533 to your computer and use it in GitHub Desktop.
M1 Project localStorage - game score example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function saveScore(name, score) { | |
// Get the string data from localStorage | |
// Convert it to an array | |
const scoreStr = localStorage.getItem('score'); | |
let scoreArr; | |
const newScore = { name: name, score: score }; | |
// Add new score to the array | |
if (!scoreStr) { | |
scoreArr = []; | |
scoreArr.push(newScore); | |
} else if (scoreStr) { | |
scoreArr = JSON.parse(scoreStr); | |
scoreArr.push(newScore); | |
} | |
// Stringify the updated score array | |
const updatedScoreStr = JSON.stringify(scoreArr); | |
// Store back the updated array string | |
localStorage.setItem('score', updatedScoreStr); | |
} | |
function getScores() { | |
const scoreStr = localStorage.getItem('score'); | |
// Add new score to the array | |
if (!scoreStr) { | |
scoreArr = []; | |
} else if (scoreStr) { | |
scoreArr = JSON.parse(scoreStr); | |
} | |
return scoreArr; | |
} | |
// saveScore('Uros', 1234); | |
const v = getScores(); | |
console.log('v', v); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment