pix*_*ons 2 javascript node.js ionic4
我有以下代码:
if (this.places.length) {
console.log(this.places);
var myData = this.places.map(({ points }) => points);
var myTotal = 0; // Variable to hold your total
for(var i = 0, len = myData.length; i < len; i++) {
myTotal += myData[i][1]; // Iterate over your first array and then grab the second element add the values up
}
console.log(myTotal);
}
Run Code Online (Sandbox Code Playgroud)
我有一个对象
,我需要从该对象中提取所有数组,并从该数组中仅提取一个特定值,例如点。
主要目标是将所有点求和并保存到一个新变量中。上面的代码不起作用。
如果我理解正确,您想计算数组points中包含的每个Place对象中所有字段的总数,this.places并将结果存储在新变量中myTotal-一种实现方法是通过reduce():
if (this.places.length) {
/* The total returned by reduce() will be stored in myTotal */
let myTotal = this.places.reduce((total, place) => {
/* For each place iterated, access the points field of the
current place being iterated and add that to the current
running total */
return total + place.points;
}, 0); /* Total is initally zero */
console.log(this.places);
console.log(myTotal);
}
Run Code Online (Sandbox Code Playgroud)