How To Return Value From Loop. Js, Vuejs
Sorry, I'm beginner with JS,i have a basic question, but i spent a whole day trying to find answer in google and i didn't. I have a massic financial instrument developed on php and
Solution 1:
You could use reduce
function which you could learn more about here:
newVue({
el: "#app",
data: {
equities: [{
name: "Serias A",
price: 20
},
{
name: "Serias B",
price: 21
},
]
},
computed: {
cashDividends() {
returnthis.equities.reduce(this.sum);
}
},
methods: {
sum(total, num) {
return total.price + num.price
}
}
});
<linkhref="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO"crossorigin="anonymous"><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/vue/2.2.1/vue.min.js"></script><divid="app">
{{cashDividends}}
</div>
Solution 2:
Use reduce function
newVue({
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)
}
}
});
Solution 3:
You can define a variable sum and iteratively add equity.price
to it as follows:
cashDividends() {
let sum = 0this.equities.forEach(function(equity)) {
sum+=equity.price
}
return sum
}
Post a Comment for "How To Return Value From Loop. Js, Vuejs"