如何将localStorage值设为true?

Goo*_*dMe 4 javascript string boolean local-storage

我想知道localStorage是否可以使用布尔值而不是字符串?

如果JS不可能,或者使用JS以不同的方式在JS中完成,请使用JS,请让我知道谢谢

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");
}

*/
Run Code Online (Sandbox Code Playgroud)

T.J*_*der 11

我想知道localStorage是否可以使用布尔值而不是字符串?

不,网络存储只存储字符串.为了存储更丰富的数据,人们通常在存储时使用JSON和stringify,并在检索时进行解析.

储存:

var test = true;
localStorage.setItem("test", JSON.stringify(test)); 
Run Code Online (Sandbox Code Playgroud)

检索:

test = JSON.parse(localStorage.getItem("test"));
console.log(typeof test); // "boolean"
Run Code Online (Sandbox Code Playgroud)

但是,您不需要JSON只是一个布尔值; 你可以使用""false和任何其他字符串表示true,因为它""是一个"falsey"值(当被视为布尔值时强制为false的值).