javascript - 未捕获的语法错误:位置 0 处的 JSON 中的意外标记 D
问题描述
我正在尝试将数据(1stName、lastName、email、password、gender 所有这些都存储在一个对象中,并且该对象在数组中)在 localStorage 中,我使用了 JSON.parse() 和 JSON.stringify() 函数。我不知道错误在哪里。请注意,我只写 javascript。这是代码:
<script>
function create(){
if(document.getElementById('fn').value!=null&&document.getElementById('fn').value!=""
&&document.getElementById('ln').value!=null&&document.getElementById('ln').value!=""
&&document.getElementById('em').value!=null&&document.getElementById('em').value!=""&&
document.getElementById('pass').value!=null&&document.getElementById('pass').value!=""){
if(document.getElementById('gender_Male').checked) {
var acc = {fname:document.getElementById('fn').value,
lname:document.getElementById('ln').value,
email:document.getElementById('em').value,
password:document.getElementById('pass').value,
gender:document.getElementById('gender_Male').value};}
else{
var acc = {fname:document.getElementById('fn').value,
lname:document.getElementById('ln').value,
email:document.getElementById('em').value,
password:document.getElementById('pass').value,
gender:document.getElementById('gender_Female').value};}
if (localStorage.getItem('acc'))
var ar = JSON.parse(localStorage.getItem('acc'));
else
var ar = [];
ar.push(acc);
localStorage.setItem('acc',JSON.stringify(ar));
}
else window.alert("One of the above is empty");
}
</script>
解决方案
只需检查一下
let ar = JSON.parse(localStorage.getItem('acc') || []);
ar.push(acc);
localStorage.setItem('acc',JSON.stringify(ar));
推荐阅读
- python - 嵌套字典格式化输出问题
- python - tkinter wait_variable 不会回调 intvar 更改
- react-jsonschema-forms - 反应json模式表单不发送空值键
- javascript - 我需要重新加载我的页面以显示 CKEDITOR
- python - 嵌套列表理解返回列表列表而不是单个列表
- python - 如何在 VS Code 中配置 python 大纲模式以仅显示类和方法
- sql - 自动刷新来自 Excel 工作表的 SQL 数据库数据
- css - 减小列表项宽度以在 Internet Explorer 11 中占据文本内容的确切大小
- python - 从列表中删除元素时遇到问题
- powerbi - Power BI 与 Databricks 方法的连接