【发布时间】:2018-02-25 00:08:09
【问题描述】:
【问题讨论】:
-
在打字稿中迭代的大量选项; typescriptlang.org/docs/handbook/iterators-and-generators.html。例如,为总数创建一个新属性,然后使用
for..of遍历每个对象并将每个cart_subtotal添加到总数中。
标签: angular typescript ionic2
【问题讨论】:
for..of 遍历每个对象并将每个cart_subtotal 添加到总数中。
标签: angular typescript ionic2
试试看,希望对你有帮助
totalAmount:number = 0;
for(let i=0;i<this.data.length;i++){
totalAmount = totalAmount + this.data[i].cart_subtotal;
}
如果cart_subtotal 给出字符串值,则使用:
totalAmount = totalAmount + parseInt(this.data[i].cart_subtotal);
【讨论】:
我认为更好(更现代)的方法是使用 reduce 函数,因为求和是 reduce 函数的典型示例。你可以这样做:
let sum = ((items, prop) => {
return arr.reduce((a, b) => {
return a + b.prop;
}, 0)
})
let sum = sum(cartInfo, 'cart_subtotal')
这不是一个经过测试/工作的示例,但应该让您很好地了解如何以实用和现代的方式实现这种行为:)
【讨论】:
您需要使用*ngFor 指令。 Here 是官方文档的链接,展示了如何使用 *ngFor 指令。在您的情况下,您需要使用对象中的属性,因此我在下面的示例中添加了属性,该示例来自 Angular 文档。您可以使用标准点表示法访问每个单独对象的属性。
来自文档
<ul>
<li *ngFor="let hero of heroes">
{{ hero.firstName }} {{ hero.lastName }}
</li>
</ul>
更新
因此,如果您只想将所有cart_subtotals 相加,那么您需要在组件中声明一个属性,然后在向数组中添加新对象时更新grandTotal。我不知道您如何将项目添加到数组中,但是每次添加新项目时都需要执行下面相应标记的部分。看起来您的小计也是字符串形式的,因此您需要先解析它们,然后才能对它们进行任何数学运算。
// Declare in your component
private grandTotal: number = 0;
// Run anytime an object is added to the array.
updateGrandTotal() {
// Instantiate a temporary new grand total variable.
let newGrandTotal = 0;
// Iterate over each cart item.
this.carts.forEach(_Cart => {
// Add the current cart subtotal to the new grand total.
newGrandTotal = newGrandTotal + parseInt(_Cart.cart_subtotal)
})
// Save the New GrandTotal to the Grand Total Property.
this.grandTotal = newGrandTotal;
}
【讨论】:
*ngFor 是 OP 正在寻找的;他们试图合计迭代项目的值,这将在打字稿中完成,而不是在 HTML 中。我确实同意,我认为这不是一个经过充分研究的问题,这就是为什么我只发表评论而没有提供官方答案的原因。