我注意到我不能在localStorage中设置布尔值
localStorage.setItem("item1", true);
alert(localStorage.getItem("item1") + " | " + (localStorage.getItem("item1") == true));当我尝试测试localStorage.getItem("item1") == "true"时,总是向true | false发出警报它发出的警报为真...如何将localStorage中的项设置为true?
即使它是一个字符串,我还以为只有===会检查类型呢?
所以
alert("true" == true); // should be true? 发布于 2010-07-16 16:41:47
目前,所有的实现Safari、WebKit、Chrome、Firefox和IE都遵循WebStorage标准的old version,其中存储项的值只能是一个字符串。
一种选择是使用JSON parse和stringify方法来序列化和反序列化数据,就像我不久前在another question中建议的那样,例如:
var value = "true";
console.log(JSON.parse(value) === true); // true
发布于 2016-05-02 16:46:53
我的解决方案:
function tytPreGetBool(pre) {
return localStorage.getItem(pre) === 'true';
}发布于 2010-07-16 17:09:55
这与CMS的答案有关。
下面是我用来处理这个问题的解析部分的一个小函数(该函数将在浏览器实现赶上规范之后继续做正确的事情,所以不需要记住稍后更改代码):
function parse(type) {
return typeof type == 'string' ? JSON.parse(type) : type;
}https://stackoverflow.com/questions/3263161
复制相似问题