我需要为购物篮添加总金额,但我不知道如何在jade中实现这一点。
这是我认为可以实现的方法,但它不起作用,我尝试过的其他方法都会出现错误。
有人知道我该如何做吗?
each item in bagItems
- var total = total + item.realprice
p= total
p= bagItems.reduce(function(total, item) { return total + item.realprice; }, 0)
Prestaul的reduce
答案是一个好的解决方案,但我想回答一下,以便让你更深入地了解发生了什么。
问题在于,在each
循环内创建的变量在循环外部不可用。在JavaScript中,您的代码将如下所示:
bagItems.forEach(function(item) {
var total = total + item.realprice;
});
write("<p>" + total + "</p>");
我假设你熟悉JS的变量作用域,但基本上在函数内定义的var
在外部是不可访问的。
第二个问题是你把total定义为它自己加上其他东西,但你从未给它一个初始值,所以它最终会成为undefined + item.realprice
,这是NaN
。
这里是另一种解决方案,可以解决这两个问题:
- var total = 0
each item in bagItems
- total += item.realprice
p= total