本文介绍了无法在LocalStorage中设置布尔值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我注意到我无法在 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. (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日草案匹配现有实现的行为,因为没有供应商对支持存储非字符串感兴趣。请参见 https://www.w3.org/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 https://www.w3.org/Bugs/Public/show_bug.cgi?id=12111 for detail. 这篇关于无法在LocalStorage中设置布尔值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
07-25 03:19