Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
483 views
in Technique[技术] by (71.8m points)

javascript - localStorage and boolean 'string'

Storing boolean value in localStorage, this value is converted to string. Now trying to converting back this value from localStorage to boolean, i need to use JSON.parse() method, the more handy !! doesn't work.

Code sample:

var test = false;
localStorage['test'] = test;
console.log("JSON.parse returns: ", JSON.parse(localStorage['test']), "expected: ", test);
console.log("'!!' returns: ", !! localStorage['test'], "expected: ", test);

-jsFiddle-

I'm quite confused why this behaviour. Any explaination?

PS: using getter/setter localStorage methods doesn't matter here, same result.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Local storage stores strings , I'm afraid, whatever the input (if you feed it with an object, it will be converted automatically with its standard toString() method)... So you're doing !! test on a string, which is always true.

You should always use JSON.stringify() and JSON.parse() when dealing with what you store in DOM storage


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...