为什么本地存储必须是字符串?

Qam*_*ala 5 html session-storage local-storage

我知道在 window.localStorage 或 window.sessionStorage 中设置项目时,需要首先将其转换为字符串。我只是想知道……为什么要这样设计?我尝试用谷歌搜索,但找不到任何关于原因的文章;我发现的主要是关于如何设置 localStorage 的文章。

小智 -1

我认为你总是得到一个字符串,但你可以保存任何值,你可以使用开发人员工具控制台查看日志输出:

<script type="text/javascript">
    //Store
    localStorage.setItem("integer", 1);
    localStorage.setItem("float", 1.5);
    localStorage.setItem("string", "Hello");
    localStorage.setItem("array", [1, 2, 3, 4, 5]);

    //Retrieve
    console.log(localStorage.getItem("integer")==="1");
    console.log(localStorage.getItem("float")==="1.5");
    console.log(localStorage.getItem("string")==="Hello");
    console.log(localStorage.getItem("array")==="1,2,3,4,5");
</script>
Run Code Online (Sandbox Code Playgroud)

输出:

在此输入图像描述