5👍
✅
inside the callback function that you passed to forEach
, this
does nto point to the component, it is undefined
by default.
https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
the callback function receives each todo
as the argument, so an example would look like this:
totale: function(){
var total = 0;
this.todos.forEach(function (todo) {
total += todo.price
});
return total;
}
Generally, I would not use forEach, I would use reduce. Together with an arrow function it becomes a nice one-liner:
totale: function () {
return this.todos.reduce((sum, todo) => sum + todo.price, 0)
}
3👍
Wrong use of forEach
e.g.
var total = 0;
var arrayOfObjects = [{price: 10},{price: 20},{price : 30}];
// Correct usage:
arrayOfObjects.forEach(function(obj) {
total += obj.price;
})
console.log(total)
0👍
Replace code
this.todos.forEach(function(){
total += this.todos.price
});
to
this.todos.forEach(function(data){
total += data.price
});
Source:stackexchange.com