I have two functions that save variables to LocalStorage. The first one saves a variable, "money", but the second doesn't. The global variable "money" does not get assigned.
function saveVars() {
localStorage.setItem('money', money);
}
function loadVars() {
var money = localStorage.getItem('money');
}
From your example, I can assume two alternatives :
1) you want to "load" the value into a global variable named "money" ? Your code doesn't work because you declare a local variable "money" that only exists within the function loadVars
. Don't declare your variable (i.e. do not add the keyword var
or any equivalent in the function). The assignment money = …
will assign to the global variable "money" only if there is no other variable named "money" in a more specific scope — and it will do so even if the global variable was not declared.
function loadVars() {
money = localStorage.getItem('money');
}
2) you want loadVars
to return the value of the stored variable ? and then you can assign that to a global:
function loadVars() {
return localStorage.getItem('money');
}
var money = loadVars();
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments