最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - localStorage and boolean 'string' - Stack Overflow

programmeradmin2浏览0评论

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.

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.

Share Improve this question edited Jun 20, 2020 at 9:12 CommunityBot 11 silver badge asked Jun 4, 2015 at 12:46 A. WolffA. Wolff 74.4k9 gold badges96 silver badges156 bronze badges 2
  • because !!"false"===true – epascarello Commented Jun 4, 2015 at 12:50
  • stackoverflow.com/questions/263965/… – epascarello Commented Jun 4, 2015 at 12:51
Add a comment  | 

4 Answers 4

Reset to default 20

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

Use JSON.stringify() when save the object. As you know it will convert JavaScript value to a JSON string so when using JSON.parse() its converted back properly.

localStorage['test'] = JSON.stringify(test);

DEMO

This happens because any stored value in localstorage is a string. So you've perofming !!"false" and !! is always true for non-empty string. To be able to store non-string values in localStorage you have to always use JSON.

What you want to do is simple with localDataStorage, where you can transparently set/get any of the following "types": Array, Boolean, Date, Float, Integer, Null, Object or String.

[DISCLAIMER] I am the author of the utility [/DISCLAIMER]

Examples:

localDataStorage.set( 'test', false );

localDataStorage.get( 'test' );   -->   false

All of the conversion work is done in the background for you: just set/get and go.

发布评论

评论列表(0)

  1. 暂无评论