Context
- I am not a developer
- I want to use Vanilla JS (no JQuery)
I’m using the following code and it is giving me the desired outcome, however I’d like to improve the code and make it more efficient if possible.
Working code
var score_A1 = localStorage.getItem("score_A1");
var score_A2 = localStorage.getItem("score_A2");
var score_A3 = localStorage.getItem("score_A3");
var score_A4 = localStorage.getItem("score_A4");
var score_A5 = localStorage.getItem("score_A5");
a =+ score_A1;
b =+ score_A2;
c =+ score_A3;
d =+ score_A4;
e =+ score_A5;
var scoreTotal_A = a + b + c + d + e;
I am then using innerHTML and calling ${scoreTotal_A} to display the total.
Questions
- Is there a ‘better’, more efficient way to code this?
- Is there a way to code it to GET and ADD together any localStorage item that begins with
score_A?
Thanks in advance for any help.
>Solution :
You can use the .key() method to iterate through local storage keys:
function sumScores() {
let key, sum = 0;
for (let i = 0; (key = localStorage.key(i)) != null; ++i)
if (/^score_A/.test(key))
sum += +localStorage.getItem(key);
return sum;
}
Then call it like
console.log("All A score total: " + sumScores());