Javascript 尝试使用For函数获取一些信息
我正在进行一个角度项目,我想捕捉所有的encCharge,并将它们添加到cf中的所有encCharge中,并使用for函数 这是我的阵列:Javascript 尝试使用For函数获取一些信息,javascript,angular,typescript,for-loop,Javascript,Angular,Typescript,For Loop,我正在进行一个角度项目,我想捕捉所有的encCharge,并将它们添加到cf中的所有encCharge中,并使用for函数 这是我的阵列: produits = [ { cf1: { cfTitle: 'prInfiniti30j', encCharge: 12345.75, encBonifie: 47730.56 }, cf2: { cfTitle: 'prInfiniti30j',
produits = [
{
cf1: {
cfTitle: 'prInfiniti30j',
encCharge: 12345.75,
encBonifie: 47730.56
},
cf2: {
cfTitle: 'prInfiniti30j',
encCharge: 18400.94,
encBonifie: 38268.56
},
cf3: {
cfTitle: 'prInfiniti30j',
encCharge: 18392.00,
encBonifie: 30570.56
},
cf4: {
cfTitle: 'prInfiniti30j',
encCharge: 0.00,
encBonifie: 15230.56
},
},
];
这是我的功能和我尝试过的东西,但我找不到我想要的
ngOnInit(){
for (let testing in this.produits[0]) {
console.log(this.produits[0].cf1.encBonifie);
// console.log(this.produits[0].testing.encCharge);
// console.log(testing.encCharge);
}`
这是我期望的结果:
let totalEncCharge = this.produits[0].cf1.encCharge +
this.produits[0].cf2.encCharge + this.produits[0].cf3.encCharge +
this.produits[0].cf4.encCharge ;
console.log(totalEncCharge);
谢谢你的帮助请看一看,希望对你有帮助
ngOnInit(){
let totalEncCharge = 0;
for (let i = 0 ; i < this.produits.length; i++) {
let key = 'cf'+(i+1);
totalEncCharge = totalEncCharge + this.produits[i].key.encCharge
}
console.log(totalEncCharge);
}
ngOnInit(){
设TotalEnCharge=0;
for(设i=0;i
以下操作应通过Object.values()
首先从内部对象获取值。之后,您可以使用reduce将它们简单地相加
var produits=[{cf1:{cfTitle:'prInfiniti30j',encCharge:12345.75,encBonifie:47730.56},cf2:{cfTitle:'prInfiniti30j',encCharge:18400.94,encBonifie:38268.56},cf3:{cfTitle:'prInfiniti30j',encCharge:18392.00,encBonifie:30570.56},cf4:{cfTitle:'prInfiniti30j',encCharge:0.00,encBonifie:15230.56},]
让totalEncCharge=Object.values(产品[0]).reduce((a,c)=>a+=c.encCharge,0)
控制台日志(总费用)代码>您也可以尝试使用对象.键
var total = 0;
Object.keys(this.produits[0]).map(item=>{
total+=this.produits[0][item].encCharge });
console.log(total);
*编辑:如果您不希望返回任何值,而是像示例中那样设置一些其他属性,那么最好使用forEach
而不是map
,您可以使用一种方法来聚合总计
const pluck = (a) => a.encCharge;
const sum = (a, b) => a + b;
const total = Object.values(this.produits[0])
.map(pluck)
.reduce(sum, 0);
而不是:console.log(this.produits[0].cf1.encBonifie)
,使用测试变量,如:console.log(this.produits[0][testing].encBonifie)代码>考虑只在for
循环中记录console.log(JSON.stringify(testing))
。另外,对数组使用for..in
也不是不好的做法。看,我认为TotalEnCharge将只加载循环中的最后一个值,应该是这样的?```设TotalEnCharge=0;对于(设i=0;iforEach
而不是map
。是的,你是对的,使用forEach
是更好的方法。你知道为什么我不能在HTML中调用变量吗?比如当I{{total}在HTML页面上没有显示任何内容时,它是在ngOnInit中的正确位置还是应该在构造函数中?感谢您的帮助,要在模板中使用它,它需要是一个类属性,也就是说,在类的任何方法之外定义。声明一个变量,例如public total:number代码>在你的类声明下,然后在你的计算下执行this.total=total
。@assoron啊,我明白了<代码>产品
是一个数组。谢谢。将Object.values(this.produits)
更改为Object.values(this.produits[0])
,它将返回一个数字,而不是NaN。在使用for。。。在
中,以防止副作用。看看这个问题: