【发布时间】:2021-06-28 14:20:31
【问题描述】:
我有两个数组,一个数组在包含随机数yIsGiven() 的数组中只有一个属性,如 y 和一个数组,它等于第一个数组,但有一个区别,此时我的所有属性都是y 除了一个,还有一个 z,还有随机数zIsGiven()。
我的目标是将所有这些都计算在一起,在我的第一个数组上它工作得很好,但在我的第二个数组中它不起作用只是因为我将一个 y 属性更改为 z 并且我得到 NaN.
我想将数组中的所有值相加,我该如何使用zIsGiven()?
我的 app.component.html:
<h4>My array is in total:</h4>
<p>{{yIsGiven()}}</p>
<h4>But if I change my attribute from y to z I get:</h4>
<p>{{zIsGiven()}}</p>
我的 app.component.ts:
yIsGiven() {
var temp = [
{
name: "Agency",
y: 110, /* All attributes are y */
drilldown: {
name: "Agency",
categories: ["APPS & SI", "ERS"],
data: [24, 8]
}
},
{
name: "ER",
y: 60,
drilldown: {
name: "ER",
categories: ["APPS & SI", "ERS"],
data: [7, 53]
}
},
{
name: "Direct",
y: 60,
drilldown: {
name: "Direct",
categories: ["APPS & SI", "ERS"],
data: [31, 29]
}
}
];
var reduced = temp
.map(function(obj) {
return obj.y;
})
.reduce(function(a, b) {
return a + b;
});
return reduced;
}
zIsGiven() {
var temp = [
{
name: "Agency",
z: 110 /* For example this is now z and not y */,
drilldown: {
name: "Agency",
categories: ["APPS & SI", "ERS"],
data: [24, 8]
}
},
{
name: "ER",
y: 60,
drilldown: {
name: "ER",
categories: ["APPS & SI", "ERS"],
data: [7, 53]
}
},
{
name: "Direct",
y: 60,
drilldown: {
name: "Direct",
categories: ["APPS & SI", "ERS"],
data: [31, 29]
}
}
];
var reduced = temp
.map(function(obj) {
return obj.y;
})
.reduce(function(a, b) {
return a + b;
});
return reduced;
}
如果我只更改一个值,我就无法汇总数组中的所有值,但是如果我的数组中有不同的属性要汇总怎么办?它只是不适用于数组减少,或者我无法弄清楚。
感谢您的每一个帮助,谢谢!
工作: https://stackblitz.com/edit/angular-ivy-tanetr?file=src%2Fapp%2Fapp.component.html
最好的问候
【问题讨论】:
标签: arrays angular typescript reduce