0

I am trying to make a value, called Iron, increase every second whilst in localStorage, but the value just adds a 1 on the end instead of increasing by 1.

HTML:

<div id="iron"></div>

Javascript:

var material1= "0";
localStorage.setItem("Iron","1");
window.setInterval(
     function () {
         material1 = material1 + 1;
        localStorage.setItem("Iron",material1);
         document.getElementById("iron").innerHTML = 'Current Iron Supply is: ' + localStorage.getItem("Iron");
     }, 1000);
</script> 
Peter B
  • 22,460
  • 5
  • 32
  • 69
Steelmache
  • 13
  • 2
  • Do note: localstorage only stores _strings_. That's why you need to convert the value to a number, preferably using `Number()`, as in `Number(valueFromLocalStorage)`; – Rickard Elimää Dec 16 '20 at 13:12
  • @RickardElimää I have been using localStorage as a number holder and have had no problems displaying it. Will this affect my code further on? – Steelmache Dec 19 '20 at 23:01
  • Javascript is very forgiving when it comes to interpret types (strings, numbers, objects, etc.) so it shouldn't be any problem, unless you use `+` to add two numbers together, as you already experienced. `localStorage` automatically turns non-strings into strings. Just try to add an object, and you will see. – Rickard Elimää Dec 20 '20 at 00:20

1 Answers1

0

you declared material1 as string.
you should declare it as number like this: var material1= 0; and then convert it to string simply by material1+""

or parse material1 to int before the addition

ATP
  • 2,939
  • 4
  • 13
  • 34