如何将localStorage的值设置为true?

编程入门 行业动态 更新时间:2024-10-26 10:27:09
本文介绍了如何将localStorage的值设置为true?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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

仅在无法使用JS或不可以在JS中使用JSON的情况下才使用JS,请让我知道,谢谢

Using JS only no JSON if its impossible or can be done in JS a different way please let me know thanks

jsbin/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并进行字符串化,而在检索时进行解析.

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,因为""是一个假"值(当被视为布尔值时,该值将强制转换为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?

本文发布于:2023-11-12 01:27:47,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1580123.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:设置为   如何将   localStorage   true

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!