为什么将null作为字符串存储在localStorage中? [英] Why is null stored as a string in localStorage?

查看:375
本文介绍了为什么将null作为字符串存储在localStorage中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Chrome控制台中,我将foo设置为null:

In the Chrome console I set foo to null:

localStorage.setItem("foo",null)

然后我测试是否为空:

console.log(localStorage.getItem("foo")==null)

打印false.

然后我测试是否是字符串"null":

Then I test, whether it is the string "null":

console.log(localStorage.getItem("foo")=="null")

打印true.

我认为null是合法的Javascript值.当我在浏览器中手动清除localStorage时,将其存储为字符串"null"非常直观,并且在其他可以正常运行的程序中引起了奇怪的错误.

I thought that null was a legitimate Javascript value. Storing it as the string "null" is very counter intuitive and caused a strange bug in an otherwise working program, when I cleared the localStorage in the browser manually.

推荐答案

按照 setter 方法转换为setItem,仅接受DOMString

setter method translates to setItem, accepts only DOMString

根据文档

DOMString是UTF-16字符串.由于JavaScript已经使用了这样的字符串, DOMString直接映射到字符串.

DOMString is a UTF-16 String. As JavaScript already uses such strings, DOMString is mapped directly to a String.

将null传递给通常接受DOMString的方法或参数 字符串化为"null".

Passing null to a method or parameter accepting a DOMString typically stringifies to "null".

这篇关于为什么将null作为字符串存储在localStorage中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆