无法在LocalStorage中设置布尔值?

编程入门 行业动态 更新时间:2024-10-21 06:44:22
本文介绍了无法在LocalStorage中设置布尔值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我注意到我无法在 localStorage 中设置布尔值?

i noticed that i cannot set boolean values in localStorage?

localStorage.setItem("item1", true); alert(localStorage.getItem("item1") + " | " + (localStorage.getItem("item1") == true));

始终提醒 true | false 当我尝试测试 localStorage.getItem(item1)==true时它会发出警告......所以我无能为力将 localStorage 中的项目设置为true?

always alerts true | false when i try to test localStorage.getItem("item1") == "true" it alerts true ... so no way i can set an item in localStorage to true?

即使它是一个字符串,我认为只有 === 会检查类型吗?

even if its a string, i thought only === will check the type?

所以

alert("true" == true); // shld be true?

推荐答案

Firefox的存储实现只能存储字符串,但是在 2009年9月,W3C修改了草案以接受任何数据。 实现(仍然)尚未赶上(请参阅下面的编辑)。

Firefox's implementation of Storage can only store strings, but on 2009 September, W3C modified the draft to accept any data. The implementation (still) isn't caught up yet (see Edit below).

所以在你的情况下boolean转换为字符串。

So in your case the boolean is converted to a string.

至于为什么true!= true ,如 Equal的描述( == )在MDC中 *:

As for why "true" != true, as written in the description of Equal (==) in MDC*:

如果两个操作数的类型不同,则JavaScript转换操作数然后应用严格比较。如果操作数是数字或布尔值,则操作数将转换为数字(如果可能);否则,如果任一操作数是一个字符串,则另一个操作数将转换为字符串(如果可能)。

If the two operands are not of the same type, JavaScript converts the operands then applies strict comparison. If either operand is a number or a boolean, the operands are converted to numbers if possible; else if either operand is a string, the other operand is converted to a string if possible.

请注意,该字符串将转换为 Number 而不是 Boolean 。由于true转换为数字是 NaN ,它不会等于任何东西,所以 false 。

Note that the string is converted to a Number instead of a Boolean. Since "true" converted to a number is NaN, it will not be equal to anything, so false is returned.

(*:有关实际标准,请参阅ECMA-262§ 11.9.3抽象平等比较算法)

(*: For the actual standard, see ECMA-262 §11.9.3 "The Abstract Equality Comparison Algorithm")

编辑: setItem 接口已恢复为仅接受 2011年9月1日草案匹配现有实现的行为,因为没有供应商对支持存储非字符串感兴趣。请参见 www.w3/Bugs/Public/show_bug。 cgi?id = 12111 了解详情。

The setItem interface was reverted to accept strings only on the 2011 Sept 1st draft to match the behavior of existing implementations, as none of the vendors are interested in supporting storing non-strings. See www.w3/Bugs/Public/show_bug.cgi?id=12111 for detail.

更多推荐

无法在LocalStorage中设置布尔值?

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

发布评论

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

>www.elefans.com

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