![](/img/trans.png)
[英]“Cannot set property of undefined”, even though array has already been initialized
[英]Cannot add into an already initialized array
document.getElementById('form').addEventListener('submit', saveItem);
function saveItem(e){
var items= document.getElementById('items').value;
var date= document.getElementById('date').value;
var price= document.getElementById('price').value;
var expense= {
items: items,
date: date,
price: price
}
if(localStorage.getItem('bill')==null){
var bill=[];
bill.push(expense);
localStorage.setItem('bill', JSON.stringify(expense));
} else{
var bill = JSON.parse(localStorage.getItem('bill'));
bill.push(expense);
localStorage.setItem('bill', JSON.stringify(expense));
console.log(bill);
}
e.preventDefault();
}
如果沒有錯誤
if(localStorage.getItem('bill')==null)
但是其他地方出現了錯誤
Uncaught TypeError: Cannot read property 'push' of undefined
at HTMLFormElement.saveItem
當本地存儲空時存儲數據但如果不存儲則不能添加數據。
你能否檢查一下JSON.parse(localStorage.getItem('bill'));
的結果是什么JSON.parse(localStorage.getItem('bill'));
? 它是一個有效的數組嗎?
您的費用是一個對象,您需要將帳單保存在本地存儲中。
if(localStorage.getItem('bill')==null){
var bill=[];
bill.push(expense);
localStorage.setItem('bill', JSON.stringify(bill));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.