首页 > 解决方案 > 未捕获的语法错误:位置 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>

标签: javascriptjson

解决方案


只需检查一下

let ar = JSON.parse(localStorage.getItem('acc') || []);
ar.push(acc);   
localStorage.setItem('acc',JSON.stringify(ar));

推荐阅读