如何让 localStorage 值为真?

How to have localStorage value of true?

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

只使用 JS 不使用 JSON 如果不可能或可以用 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");
}

*/

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

不,web storage 只存储字符串。为了存储更丰富的数据,人们通常在存储时使用 JSON 并在检索时使用 stringify。

存储:

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

正在检索:

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

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