[英]Check if local storage value is equal to
I would like to know how to check a the value of an item stored in local storage is true or false. 我想知道如何检查存储在本地存储中的项目的值为true或false。
This is what i have , but the if statement isnt working. 这就是我所拥有的,但是if语句不起作用。
function setCBT(){
localStorage.setItem('testObject', true);
}
function alertLocalStorage(){
var object = localStorage.getItem('testObject');
if(object == true) {
alert("This item is true");
}
else {
alert("This item is false");
}
}
all the implementations Safari, WebKit, Chorme, Firefox and IE, are following an old version of the WebStorage standard, where the value of the storage items can be only a string.
Safari,WebKit,Chorme,Firefox和IE的所有实现都遵循WebStorage标准的旧版本,其中存储项的值只能是字符串。
Thus you need to compare the value with string: 因此,您需要将值与字符串进行比较:
if(object == "true") {
Here is the Alternative posted by CMS . 这是CMS发布的替代方案 。
You can simply use 您可以简单地使用
if(object) {
// true
}
Why not use JSON.parse()
.The JSON.parse()
method parses a string as JSON, optionally transforming the value produced by parsing. 为什么不使用
JSON.parse()
. JSON.parse()
方法将字符串解析为JSON,可以选择转换解析产生的值。
if(JSON.parse(object)) {
alert("This item is true");
}
Note using JSON.parse() 注意使用JSON.parse()
JSON.parse('{}'); // {}
JSON.parse('true'); // true
JSON.parse('"foo"'); // "foo"
JSON.parse('[1, 5, "false"]'); // [1, 5, "false"]
JSON.parse('null'); // null
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.