Retrieve integer from localStorage JS in Chrome

0

I am saving a localStorage in the following way and I paint it in <p> ;

var punt1=document.getElementById("puntJ1");
var punt2=document.getElementById("puntJ2");

function pintarPuntosJugadores(){
if(localStorage.getItem("jugador1")==null){
    localStorage.setItem("jugador1","0");
    localStorage.setItem("jugador2","0");
}
punt1.textContent=localStorage.getItem("jugador1");
punt2.textContent=localStorage.getItem("jugador2");   
}

The result when I load the page is 0, the problem comes when I want to increase that 0 to a 1 then 2 etc ... as one player or another wins.

function Ganador(){

let jugador="";
if(turno){
    jugador="jugador1";
}else{
    jugador="jugador2";
}
alert(jugador+" Ha ganado");
let puntJugAct=localStorage.getItem(jugador);
//let result=parseInt(puntJugAct) +1;
console.log(typeof(puntJugAct));
console.log(parseInt(puntJugAct)  + 1);

localStorage.setItem(jugador,puntJugAct);
pintarPuntosJugadores();

}

The problem is that the recovered type is object and if I do console.log(parseInt(puntJugAct) + 1); the result thrown at me is NAN

While doing console.log(puntJugAct + 1); , concatenates the string recovered from the localStorage (0) with the 1 that I want to add, yielding a result like: 01

How could you transform that recovered value to int to operate with the?

    
asked by Hector Lopez 24.10.2018 в 14:00
source

1 answer

1

Try to do your same code and I gave the same error, and I saw that I was giving that NaN because when you tried to add the value contained in localStorage.getItem(jugador) did not have any value or even 0, so initialize that localstorage with 0 and then if I could add it successfully, it should look like this:

var punt1=document.getElementById("puntJ1");
var punt2=document.getElementById("puntJ2");
localStorage.setItem("jugador1","0");
localStorage.setItem("jugador2","0");

and then if you can add like this:

let puntJugAct = parseInt(localStorage.getItem(jugador)) + 1;

You can see the example working here .

is also time to initialize them at 0 you can place a condition like this:

isNaN(parseInt(localStorage.getItem(jugador)))

With this you define that if the value that is in that localstorage is a NaN , you set it to 0, thus:

let puntJugAct =  (isNaN(parseInt(localStorage.getItem(jugador)))) ? 0 : parseInt(localStorage.getItem(jugador));

I hope it serves you.

    
answered by 24.10.2018 / 17:00
source