gpt4 book ai didi

javascript - 如何让 localStorage 值为真?

转载 作者:搜寻专家 更新时间:2023-11-01 04:56:52 25 4
gpt4 key购买 nike

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

如果不可能或者可以用 JS 以不同的方式完成,请仅使用 JS 而不使用 JSON,请告诉我,谢谢

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 只是一个 boolean 值;您可以只使用 "" 表示 false,使用任何其他字符串表示 true,因为 "" 是一个“falsey”值(当被视为 boolean 值时强制为 false 的值).

关于javascript - 如何让 localStorage 值为真?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28926997/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com