javascript - 无法添加到已初始化的数组中

标签 javascript arrays

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/

相关文章:

javascript - 当用户在javascript中按下 "tab"(破折号)键时如何自动按下 "-"键

python - 如何使用 numpy 保存和读回多维字符串数组(可能)?

jquery - 尝试清除所有标记时,谷歌地图 v3 setMap 未定义

javascript - 使用JS向表单添加输入

javascript - 使用 Json 填充剑道树

C++搜索数组中的最大数字

java - 如何使用变量来指定数组长度?

arrays - 液体标记贴图过滤器示例

javascript - 如何从全局变量正确填充 javascript 对象

javascript - Laravel 多次插入到一张表中