How to have localStorage value of true?(如何使 localStorage 值为 true?)
问题描述
我想知道 localStorage 是否有可能使用布尔值而不是字符串?
I was wondering if its possible for localStorage to have a Boolean value instead of a string?
如果不可能或可以在 JS 中以不同的方式完成,请仅使用 JS 不使用 JSON,请告诉我,谢谢
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");
}
*/
推荐答案
我想知道 localStorage 是否可以使用布尔值而不是字符串?
I was wondering if its possible for localStorage to have a Boolean value instead of a string?
不,网络存储 只存储字符串.为了存储更丰富的数据,人们通常在存储时使用 JSON 和 stringify,在检索时使用解析.
No, web storage only stores strings. To store more rich data, people typically use JSON and stringify when storing and parse when retrieving.
存储:
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 的值).
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).
这篇关于如何使 localStorage 值为 true?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使 localStorage 值为 true?
基础教程推荐
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- 如何在特定日期之前获取消息? 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
