我在下面进行了重复的这些数学计算,我试图弄清楚如何使它们变干。
const d = store.state.logbook.summary,
AIR = ([d.AIR/d.TOT]*100).toFixed(2),
PIC = ([d.PIC/d.TOT]*100).toFixed(2),
PMC = ([d.PMC/d.TOT]*100).toFixed(2),
VO = ([d.VO/d.TOT]*100).toFixed(2),
TRNG = ([d.TRNG/d.TOT]*100).toFixed(2);
this.chartData = [
100, +AIR, +PIC, +PMC, +VO, +TRNG
]
console.log(this.chartData)
// Returns: [100, 97.44, 84.65, 84.65, 2.56, 12.79]!
答案 0 :(得分:1)
您可以获取一组键,映射计算出的值,松开100
并分配给所需的目标。
const
d = store.state.logbook.summary,
data = ['AIR', 'PIC', 'PMC', 'VO', 'TRNG'].map(k => +(d[k] * 100 / d.TOT).toFixed(2));
data.unshift(100);
this.chartData = data;
console.log(this.chartData);
从另一个角度看问题,将每个部分分成较小的单元,例如
const
getPercent = (whole, part) => part * 100 / whole,
getNumFixed2 = value => +value.toFixed(2),
d = { AIR: 28, PIC: 9, PMC: 2, VO: 56, TRNG: 25, TOT: 120 }, // store.state.logbook.summary,
data = ['AIR', 'PIC', 'PMC', 'VO', 'TRNG']
.map(k => d[k])
.map(getPercent.bind(null, d.TOT))
.map(getNumFixed2);
data.unshift(100);
console.log(data);