【问题标题】:Why wont my JSON.stringify() work with localstorage.setItem()?为什么我的 JSON.stringify() 不能与 localstorage.setItem() 一起使用?
【发布时间】:2023-03-24 05:41:01
【问题描述】:

我从页面上的表单中提取了一个对象。我将这个对象推入一个数组。

var postObj = {title:$('input').val(),body:$('textarea').val()}
postArray.push(postObj);
localstorage.setItem("posts", JSON.stringify(postArray));

但是,我刚刚收到Uncaught ReferenceError: Localstorage is not defined

在控制台中,我从测试中获得了这些响应。

postObj
Object {title: "title", body: "dog"}
postArray
[
Object
body: "dog"
title: "title"
__proto__: Object
]
JSON.stringify(postArray);
"[{"title":"title","body":"dog"}]"

我发现对类似问题的大多数回复都是使用JSON.stringify(array)。我不知道为什么当我使用JSON.stringify 作为.setItem 的数据参数时它不起作用。

【问题讨论】:

  • 这看起来像Localstorage 尚未定义的情况,但它是在此脚本运行后定义的,因此在您稍后检查它时它看起来确实是定义的,或者它总是已定义,但不在函数范围内。
  • 你应该接受一个答案来结束这个问题:)

标签: javascript jquery json local-storage


【解决方案1】:

看起来你有错字,应该是:

window.localStorage // note the camelCase name

【讨论】:

  • 谢谢。这只是一个错字。带有大写字母的 localStorage 对数组进行了字符串化。
  • 最好和最坏的错误
猜你喜欢
  • 2011-12-25
  • 2020-10-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-26
  • 2013-07-02
  • 2015-11-08
相关资源
最近更新 更多