Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get localStorage items (numbers) and add them together

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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());
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading