Javascript 无法在 LocalStorage 中设置布尔值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3263161/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:56:14  来源:igfitidea点击:

Cannot set boolean values in LocalStorage?

javascript

提问by Jiew Meng

I noticed that I cannot set boolean values in localStorage?

我注意到我不能在localStorage?

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

Always alerts true | falsewhen I try to test localStorage.getItem("item1") == "true"it alerts true ... How can I set an item in localStorageto true?

true | false当我尝试测试localStorage.getItem("item1") == "true"它时总是发出警报警报为真...如何将项目设置localStorage为真?

Even if it's a string, I thought only ===would check the type?

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

So

所以

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

采纳答案by kennytm

Firefox's implementation of Storagecan 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).

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

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

所以在你的情况下,布尔值被转换为字符串。

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

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

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 numbersif possible; else if either operand is a string, the other operand is converted to a string if possible.

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

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

请注意,字符串被转换为Number而不是Boolean。由于"true"转换为数字 is NaN,它不会等于任何东西,因此false返回。

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

(*:有关实际标准,请参阅 ECMA-262 §11.9.3 “The Abstract Equality Comparison Algorithm”)



Edit:The setIteminterface was reverted to accept strings only on the 2011 Sept 1st draftto 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=12111for detail.

编辑:setItem接口仅在2011 年 9 月 1 日草案中恢复为接受字符串以匹配现有实现的行为,因为没有一个供应商对支持存储非字符串感兴趣。有关详细信息,请参阅https://www.w3.org/Bugs/Public/show_bug.cgi?id=12111

回答by CMS

For the moment, all the implementations Safari, WebKit, Chrome, Firefoxand IE, are following an old versionof the WebStorage standard, where the value of the storage items can be only a string.

目前,Safari、WebKit、Chrome、FirefoxIE 的所有实现都遵循旧版本的 WebStorage 标准,其中存储项的值只能是一个字符串。

An option would be to use JSON parseand stringifymethod to serializeand deserializethe data, as I suggested some time ago in another question, for example:

一种选择是使用 JSONparsestringify方法来序列化序列化数据,正如我前段时间在另一个问题中建议的那样,例如:

var value = "true";
JSON.parse(value) === true; // true

回答by tyttoot

My solutions:

我的解决方案:

function tytPreGetBool(pre) {
    return localStorage.getItem(pre) === 'true';
}

回答by oldestlivingboy

This is related to CMS's answer.

这与CMS的回答有关。

Here's a little function I've been using to handle the parsing part of this issue (the function will keep doing the Right Thing after the browser implementations catch up with the spec, so no need to remember to change out code later):

这是我一直在使用的一个小函数来处理这个问题的解析部分(在浏览器实现赶上规范后,该函数将继续做正确的事情,因此以后无需记住更改代码):

function parse(type) {
   return typeof type == 'string' ? JSON.parse(type) : type;
}

回答by front-end-engnier

Use store.js:

使用store.js

localStorage.setItem('isUser', true)
localStorage.getItem('isUser') === "true" //true
npm i -D store

store.get('isUser')  //true

回答by JohnPan

What I usually do is just save the value in LocalStore as a Boolean, and then retrieve with a parsing method, just to be sure for all browsers. My method below is customized for my business logic. Sometimes I might store smth as 'no' and still need falsein return

我通常做的只是将LocalStore中的值保存为布尔值,然后使用解析方法检索,只是为了确保所有浏览器。我下面的方法是为我的业务逻辑定制的。有时我可能会将 smth 存储为“不”,但仍然需要false作为回报

function toBoolean(str) {
    if (typeof str === 'undefined' || str === null) {
        return false;
    } else if (typeof str === 'string') {           
        switch (str.toLowerCase()) {
        case 'false':
        case 'no':
        case '0':
        case "":
            return false;
        default:
            return true;
        }
    } else if (typeof str === 'number') {
        return str !== 0
    }
    else {return true;}
}

回答by deadlock

evalcan also be used carefullyunder some cases.

eval在某些情况下也可以谨慎使用。

console.log(eval("true") === true) //true

回答by Roman

I'm not sure if LocalStorage can save boolean values but I can tell you that when you do alert("true" == true);it will never evaluate to true because you are implicitly comparing a string to a boolean. That is why to set boolean values you use trueinstead of "true".

我不确定 LocalStorage 是否可以保存布尔值,但我可以告诉你,当你这样做时,alert("true" == true);它永远不会评估为真,因为你隐式地将字符串与布尔值进行比较。这就是为什么要设置您使用的布尔值true而不是"true".