How to have localStorage value of true?

青春壹個敷衍的年華 提交于 2020-05-29 02:37:13

问题


I was wondering if its possible for localStorage to have a Boolean value instead of a string?

Using JS only no JSON if its impossible or can be done in JS a different way 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");
}

*/

回答1:


I was wondering if its possible for localStorage to have a Boolean value instead of a string?

No, web storage only stores strings. To store more rich data, people typically use JSON and stringify when storing and parse when retrieving.

Storing:

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

Retrieving:

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

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



来源:https://stackoverflow.com/questions/28926997/how-to-have-localstorage-value-of-true

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!