admin管理员组文章数量:1289637
I am confused with localStorage
and how to use it with numbers and parseInt()
.
For example, I have a 'hiScore' variable and a 'score' variable. I want to have the hiScore
variable in my localStorage
localStorage takes a string variable so I have to turn it into a number with parseInt()
All my variables have already been setup without localStorage so I was wondering what would be the best way to now add localStorage.
I couldn't understand the documentation on mozilla or W3schools.
I am confused with localStorage
and how to use it with numbers and parseInt()
.
For example, I have a 'hiScore' variable and a 'score' variable. I want to have the hiScore
variable in my localStorage
localStorage takes a string variable so I have to turn it into a number with parseInt()
All my variables have already been setup without localStorage so I was wondering what would be the best way to now add localStorage.
I couldn't understand the documentation on mozilla or W3schools.
Share Improve this question edited Mar 3, 2018 at 19:27 Mogsdad 45.8k21 gold badges162 silver badges285 bronze badges asked Aug 22, 2015 at 10:05 Manu MassonManu Masson 1,7473 gold badges19 silver badges37 bronze badges2 Answers
Reset to default 8Follow this example:
localStorage.setItem("score", 123.465); //Set value
var score = localStorage.getItem("score"); ///Get value as string
//Convert
var score1 = parseInt(score)//Returns 123
var score2 = parseFloat(score)//Returns 123.465
console.log(score1,score2);
When you fetch value from localStorage
, it is returned as string. Before using them into calculations you need to convert them into numbers by using parseInt
or parseFloat
One way to preserve variable types is by using a bination of JSON.stringify and JSON.parse. For instance if you have an object with multiple variable types:
var info = {
name: 'Bob',
age: 23,
isAdmin: true
};
You would save it to localStorage using:
localStorage.setItem('memberInfo', JSON.stringify(info));
And read it back using
var info = JSON.parse(localStorage.getItem('memberInfo'));
本文标签: javascriptHow to use localStorage with numbersStack Overflow
版权声明:本文标题:javascript - How to use localStorage with numbers - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741462628a2380126.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论