localStorage and boolean #39;string#39;(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()
方法)...所以你在做 !!在字符串上测试
,它总是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
.
在处理 DOM 存储
这篇关于localStorage 和布尔“字符串"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:localStorage 和布尔“字符串"


- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- 400或500级别的HTTP响应 2022-01-01
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- Fetch API 如何获取响应体? 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- 失败的 Canvas 360 jquery 插件 2022-01-01
- Flexslider 箭头未正确显示 2022-01-01