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)
但 else 处出现错误
Uncaught TypeError: Cannot read property 'push' of undefined
at HTMLFormElement.saveItem
本地存储为空时会存储数据,非空时无法添加数据。
最佳答案
您的费用是一个对象,您需要将账单保存在本地存储中。
if(localStorage.getItem('bill')==null){
var bill=[];
bill.push(expense);
localStorage.setItem('bill', JSON.stringify(bill));
}
关于javascript - 无法添加到已初始化的数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43165989/