0

I need to set value of a variable in session storage as 0.

Then check the value of the session storage whether it is less than a constant. If so assign a value to a variable and increment the value in session storage by 1.

How can I do this, please help me with a simple example.

TKV
  • 2,533
  • 11
  • 43
  • 56
Saga Valsalan
  • 31
  • 1
  • 1

3 Answers3

2

First of all, you should always show that you have a basic understanding of what you are asking, and show the code you have tried to solve your problem.

Passing that, using javascript Web Storage is pretty simple:

var constante = 1;
sessionStorage.setItem("variable",0);

var variable = parseInt(sessionStorage.getItem("variable"),10);
if(variable < constante ){
    sessionStorage.setItem("variable",variable + 1);
}

This is a very basic example of how you can do it, you should read the W3C documentation

Paraíso
  • 384
  • 2
  • 8
0

1)set default value of variable to 0 in sessionStorage

function setDefault(){    
  if(sessionStorage['chill'] === undefined) {
     sessionStorage['chill'] = x;
  }
}
setDefault();

2)write a function to get the variable ("here variable name is chill")

function getChill() {
   return parseInt(sessionStorage["chill"]);
}

3)now write a function to increment variable chill

function incrementChill(){
  var currentValue = getChill();
  if(currentValue > CONSTANT_VALUE){
     sessionStorage['chill'] = currentValue + 1;
  }
}
WebServer
  • 1,316
  • 8
  • 12
0

I think the question is not so trivial as some said. The key here is that sessionStorage, same as localStorage only stores strings, as pointed here.

Try this code:

function f_Counter() {
  var ls_Contador_num = sessionStorage.getItem('ls_Contador_num');
  if (!ls_Contador_num) {
    ls_Contador_num = 0;
    sessionStorage.setItem('ls_Contador_num', ls_Contador_num);
  } else {
    ls_Contador_num = parseInt(sessionStorage.getItem('ls_Contador_num', ls_Contador_num)) + 1;
    sessionStorage.setItem('ls_Contador_num', ls_Contador_num);
  }
  console.log(ls_Contador_num);
}
oxk4r
  • 452
  • 6
  • 17