I would like to know how to check a the value of an item stored in local storage is true or false.
This is what i have , but the if statement isnt working.
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.
Thus you need to compare the value with string:
if(object == "true") {
Here is the Alternative posted by 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.
if(JSON.parse(object)) {
alert("This item is true");
}
Note using JSON.parse()
JSON.parse('{}'); // {}
JSON.parse('true'); // true
JSON.parse('"foo"'); // "foo"
JSON.parse('[1, 5, "false"]'); // [1, 5, "false"]
JSON.parse('null'); // null
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.