Implementing localStorage as true: a step-by-step guide.
P粉195200437
P粉195200437 2023-10-23 23:54:45
0
1
773

I wonder if localStorage can have boolean values ​​instead of strings?

Only using JS, not JSON, if it's not possible or can be done in a different way via JS, please let me know, thanks

http://jsbin.com/qiratuloqa/1/

//How to set localStorage "test" to true?

test = localStorage.getItem("test");
localStorage.setItem("test", true); 

if (test === true) {
  alert("works");
} else {
  alert("Broken");
}



/* String works fine.

test = localStorage.getItem("test");
localStorage.setItem("test", "hello"); 

if (test === "hello") {
  alert("works");
} else {
  alert("Broken");
}

*/


P粉195200437
P粉195200437

reply all(1)
P粉197639753

No, Network Storage only stores strings. To store richer data, people often use JSON and stringify when storing and parsing when retrieving.

storage:

var test = true;
localStorage.setItem("test", JSON.stringify(test));

Search:

test = JSON.parse(localStorage.getItem("test"));
console.log(typeof test); // "boolean"

You don't need JSON to get the boolean value, though; you can just use "" for false and any other string for true, since "" is a " falsey" value (a value that is forced to false when treated as a boolean).

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template