function book()
{<br/>
var name=document.getElementById('name').value;
<br/>var date=document.getElementById('date').value;
<br/>var venue=document.getElementById('venue').value;
<br>var time=document.getElementById('time').value;
<br/> var reserve=[];
<br/>
var input={
>> name:' ',<br/>
date:' ',<br/>
venue:' ',<br/>
time:' '<br/>
};
//load local storage
reserve = localStorage.getItem("arrayCache");
reserve = JSON.parse(reserve);
if(reserve === null || reserve === undefined)//run for the first time
{
input={ name:name,
date:date,
venue:venue,
time:venue
};
input=JSON.stringify(input);
alert(input);
reserve.push(input);
localStorage.setItem("arrayCache",JSON.stringify(reserve));
alert("Data successfully stored.");
}
//when array already store data
else
{
for(var x=0; x<reserve.length;x++)
{
if(date==reserve[x].date && venue==reserve[x].venue && time==reserve[x].time)
{
alert("Date and time not available for that venue!");
break;
}
else
{
input={ name:name,
date:date,
venue:venue,
time:venue
};
input=JSON.stringify(input);
alert(input);
reserve.push(input);
localStorage.setItem("arrayCache",JSON.stringify(reserve));
alert("Data successfully stored.");
break;
}
}
}
}
我的问题是当我试图存储对象时
input={ name:name,
date:date,
venue:venue,
time:venue
};
到数组reserve[]
使用reserve.push(input)
它会提示错误,说明&#34;无法读取属性&#39;推送&#39; of null&#34;,
但是当我尝试alert(input)
时,它很好地打印出整个对象,我不知道问题出在哪里。
我的预期输出将是这样的:
reserve(0)={name:name,
date:date,
venue:venue,
time:time}
以便稍后我可以与reserve(0).name == name
答案 0 :(得分:2)
您只需要实例化array
即可。
您的错误是抛出原因
reserve = localStorage.getItem("arrayCache");
reserve = JSON.parse(reserve);
不要返回array
,您需要在push
item
之前进行测试。
它在实例化之后起作用
var name ="name";
var date ="10/10/2016";
var type="text";
var reserve;
var input = {
name:name,
date:date,
type:type
};
//Test if array exist and if it's an array
reserve = ( typeof x != 'undefined' && reserve instanceof Array ) ? reserve : []
reserve.push(input);
console.log(reserve)