问题描述
我试图将对象数据中键“值”中的值求和。 谷歌搜索了很多,但无法弄清楚。 我的猜测是我没有从localStorage检索值。 编辑:而且我想将求和的值保存到localStorage ...
var storage = localStorage.getItem("Bills");
if (storage !== null) {
var data = JSON.parse(storage);
loadData(data);
var id = data.length;
} else {
id = 0;
data = [];
};
function loadData(array) {
array.forEach(function(bill) {
newItem(bill.name,bill.value,bill.id,bill.payed);
});
};
function addBill() {
modal.style.display = "none";
var bill = document.getElementById("billName").value;
var billVal = document.getElementById("billValue").value;
newItem(bill,billVal,id,false);
data.push({
name: bill,value: billVal,id: id,payed: false
});
billsTotals.innerHTML = Object.values(data).reduce((t,{ value }) => t + value,0); // ?????
localStorage.setItem("Bills",JSON.stringify(data));
};
function newItem(name,value,payed) {
if (payed == true) {
return;
}
var ul = document.getElementById("list");
var li = document.createElement("li");
li.appendChild(document.createTextNode(name + " " + value + "kr"));
li.setAttribute("id",id);
ul.appendChild(li);
bill = document.getElementById("billName").value = "";
billVal = document.getElementById("billValue").value = "";
};
我尝试在reduce之前添加.value,但无济于事:
billsTotals.innerHTML = Object.values(data.value).reduce((t,{value}) => t + value,0); // ?????
解决方法
不确定您的数据变量。但是数据变量是一个数组,那么您可以执行以下操作。
data.reduce((total,{value})=>{
return total +value
},0)