cart = [
{
"name": "item1",
"sellingprice": 30,
"barcode": 1494857
},
{
"name": "item2",
"sellingprice": 60,
"barcode": 1235858
},
{
"name": "item3",
"sellingprice": 100,
"barcode": 1568858
}
]
function totalbill(){
Object.keys(cart).forEach(key => {
total += cart[key].sellingprice;
});
console.log(total);
输出:3060100
可以手动执行
console.log(cart[0].sellingprice+cart[1].sellingprice+cart[2].sellingprice);
190输出:
也尝试使用parseInt() did word
首先,您是否尝试在totalbill方法之前声明total var ?
?然后你可以试试:
var total = 0;
function totalbill(){
Object.keys(cart).forEach(key => {
total = total + parseInt(cart[key].sellingprice);
});
你对你的数据结构有误解。
你想要的是如下所示。
const cart = [ { "name": "item1", "sellingprice": 30, "barcode": 1494857 }, { "name": "item2", "sellingprice": 60, "barcode": 1235858 }, { "name": "item3", "sellingprice": 100, "barcode": 1568858 } ];
let total = 0;
function totalbill() {
cart.forEach(c => {
total += c.sellingprice;
});
}
totalbill();
console.log('total', total);