为什么localStorage返回大小写为null且未定义的字符串值

当我将null/undefined值保存到localStorage中时。使用localStorage.getItem时收到的结果将是字符串("null" or "undefined"

localStorage.setItem("item1",null)
localStorage.setItem("item2",undefined)

const item1 = localStorage.getItem("item1")
const item2 = localStorage.getItem("item2")

console.log(item1) // The result will be "null" not null
console.log(item2) // The result will be "undefined" not undefined

任何人都可以为我解释这种情况!

yjyyjywww 回答:为什么localStorage返回大小写为null且未定义的字符串值

Js确实将其字符串化为本地存储

storage.setItem(keyName,keyValue)
  

keyName和KeyValue均为DOMString类型

     

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

     

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

我看到我们同时有2个答案,因此只添加他在mdn docsDOMString中的部分

,
  

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

     

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

查看以下内容:https://stackoverflow.com/a/47150855/10971575

,

本地存储只能保存字符串,因此存储对象要求使用JSON将它们转换为字符串。 stringify-您不能要求本地存储直接存储对象,因为它会存储“ [object Object]”,这根本不正确!

// set new item which holds a numeric value
localStorage.setItem('number',1);
// it would be a string value. localStorage only returns string value
console.log(typeof localStorage.getItem('number'));
本文链接:https://www.f2er.com/3167738.html

大家都在问