如果我有一个像这样的javascript对象:
sampleObject[
{
suite: "Clubs",
weight : 10
},
{
suite: "Spades",
weight : 6
},
{
suite: "Hearts",
weight : 2
}
];
我该如何找到重量属性的总和?
答案 0 :(得分:5)
简单的总和减少应该起作用。
var sum = sampleObject.reduce(( sum, card ) => sum + card.weight, 0 );
答案 1 :(得分:3)
您可以map
您的对象,然后reduce
它:
samplObject
=> [weight0, weight1, weight2]
[weight0, weight1, weight2]
=> weight0 + weight1 + weight2
这意味着您将初始列表转换为权重列表,然后将值一一求和。
const sampleObject = [
{
suite: "Clubs",
weight : 10
},
{
suite: "Spades",
weight : 6
},
{
suite: "Hearts",
weight : 2
}
];
let sum = sampleObject.map( el=> el.weight).reduce( (a,b) => a+b);
console.log(sum)
输出:
18
注意:
在此特定示例中,map
是开销。您可以轻松地计算总和:
let sum = sampleObject.reduce( (a,b) => a+b.weight,0);
但是对于更复杂的数据结构,总的来说,牢记map-reduce
的概念是很好的。
答案 2 :(得分:2)
使用reduce方法并将初始值作为0
传递。您还可以使用normal for循环或forEach
方法
let sampleObject = [{
suite: "Clubs",
weight: 10
},
{
suite: "Spades",
weight: 6
},
{
suite: "Hearts",
weight: 2
}
];
let sum = sampleObject.reduce(function(acc, curr) {
//Initially the value of acc will be 0
// curr is the current object in context
acc += curr.weight
return acc;
}, 0)
console.log(sum)
答案 3 :(得分:2)
sampleObject = [
{
suite: "Clubs",
weight : 10
},
{
suite: "Spades",
weight : 6
},
{
suite: "Hearts",
weight : 2
}
];
var sum = sampleObject.reduce((a, b) => a + b.weight, 0);
console.log(sum);
答案 4 :(得分:0)
由于具有对象数组,因此可以执行以下操作来访问第一个“ weight”变量:sampleObject[0].weight
。考虑到这一点,您可以使用一个简单的for循环将它们加在一起:
var sum = 0
for(var i = 0; i < sampleObject.length; i+){
sum += sampleObject[i].weight
}
console.log(sum)
答案 5 :(得分:0)
使用reduce
:
let sampleObject = [{
suite: "Clubs",
weight : 10
}, {
suite: "Spades",
weight : 6
}, {
suite: "Hearts",
weight : 2
}];
let sum = sampleObject.reduce((a, b) => a + b.weight, 0);
console.log(sum);