对不起,我是JS的初学者,我有一个基本问题,但是我花了一整天的时间试图在google中找到答案,但是我没有。
我有一个基于php开发的大规模金融工具,我需要构建一个复杂的金融计算器来显示具有反应性的所有内容。我需要帮助找出如何在循环内使用许多if
语句进行复杂的计算,然后对数组中每个对象的输出值求和并返回总和。为此使用Vuejs。
所以我的cashDividends()
必须是循环中每个对象的计算值之和。
下面,我放置了一段代码来理解我所面临的问题。
请检查一下。谢谢!
new Vue({
el: "#waterfall",
data() {
return {
info: {
cash_dividends: true,
converted_liabilities: true,
},
equities: [
@foreach($preferredEquities as $equity)
{ name: '{{ $equity->name }}', id: {{ $equity->id }} },
@endforeach
]
}
},
computed: {
remainingExit () {
return this.form.exit_value - this.form.uncovered_debt - this.form.transaction_fees
},
cashDividends() {
//I supposed should be something like this.
this.equities.forEach(function(equity)
{
//Here I make a lot of calculations with bunch of if statements using object and DOM input values. for each object
}
// And here I need to return sum of calculated values from each object (equity) in array
}
},
答案 0 :(得分:2)
您可以使用reduce
函数,您可以了解有关here的更多信息:
new Vue({
el: "#app",
data: {
equities: [{
name: "Serias A",
price: 20
},
{
name: "Serias B",
price: 21
},
]
},
computed: {
cashDividends() {
return this.equities.reduce(this.sum);
}
},
methods: {
sum(total, num) {
return total.price + num.price
}
}
});
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.2.1/vue.min.js"></script>
<div id="app">
{{cashDividends}}
</div>
答案 1 :(得分:1)
使用reduce函数
new Vue({
el: "#waterfall",
data: {
equities: [
{name: "Serias A", price: '20'},
{name: "Serias B", price: '21'},
]
},
computed: {
cashDividends() {
var sum = this.equities.reduce(function(acc, equity) {
return acc + parseInt(equity.price);
}, 0)
}
}
});
答案 2 :(得分:0)
您可以定义一个变量总和,并将equity.price
迭代添加如下:
cashDividends() {
let sum = 0
this.equities.forEach(function(equity)) {
sum+=equity.price
}
return sum
}