localStorage和布尔“字符串" [英] localStorage and boolean 'string'

查看:130
本文介绍了localStorage和布尔“字符串"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将布尔值存储在localStorage中,此值将转换为字符串. 现在尝试将该值从localStorage转换回布尔值,我需要使用JSON.parse()方法,更方便的!!不起作用.

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.

代码示例:

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:在这里使用getter/setter localStorage方法并不重要,结果相同.

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

推荐答案

无论输入如何,本地存储都会存储字符串(如果您将其与对象一起输入,它将自动以其标准toString()进行转换)方法)...因此,您正在对字符串进行!! test,该字符串始终为true.

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.

处理存储在JSON.stringify()和JSON.parse() "noreferrer"> DOM存储

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

这篇关于localStorage和布尔“字符串"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆