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 badges
Add a ment  | 

2 Answers 2

Reset to default 8

Follow 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