我目前正在做一个简单的骰子掷骰子应用,我有以下对象:
die = [
{
ofWhat: 6,
score: [6]
},
{
ofWhat: 6,
score: [1]
},
{
ofWhat: 6,
score: [5]
}
]
我想获取每个score
并将它们组合为一个值,这样我就可以看到该数组中每个分数的总和。
像这样:6+1+5
我该如何实现?
我尝试过的事情:
total = 0;
this.die.forEach((die) => {
die.score.forEach((score) => {
this.total += score;
});
});
我得到NaN
编辑:我在对象中犯了一个错误
die = [
{
ofWhat: 6,
score: [6]
},
{
ofWhat: 6,
score: [1]
},
{
ofWhat: 6,
score: [5]
}
]
total = 0;
this.die.forEach((die) => {
die.score.forEach((score) => {
this.total += score;
});
});
console.log(total)
答案 0 :(得分:2)
尝试一下
let die = [
{
ofWhat: 6,
score: [6]
},
{
ofWhat: 6,
score: [1]
},
{
ofWhat: 6,
score: [5]
}
];
let sum = 0;
die.forEach(i => {
i.score.forEach(val => {
sum += val;
});
});
console.log(sum);
答案 1 :(得分:1)
您可以使用减速器
die = [
{
ofWhat: 6,
score: 6
},
{
ofWhat: 6,
score: 1
},
{
ofWhat: 6,
score: 5
}
]
console.log(die.reduce((acc, curr) => {
acc += curr.score;
return acc;
}, 0))
答案 2 :(得分:1)
由于您要使用this.die.forEach
从数组中取出每个对象,因此可以像访问普通对象一样访问对象的内容:object.property
die = [
{
ofWhat: 6,
score: 6
},
{
ofWhat: 6,
score: 1
},
{
ofWhat: 6,
score: 5
}
]
total = 0;
this.die.forEach((obj) => {
this.total += obj.score;
});
console.log("total score from die array: " + total)
答案 3 :(得分:1)
var die = [{
ofWhat: 6,
score: 6
},
{
ofWhat: 6,
score: 1
},
{
ofWhat: 6,
score: 5
}
];
var sum = 0;
die.forEach(element => {
sum += element.score;
});
答案 4 :(得分:1)
您可以使用两个.reduce()
方法,最里面的reduce()
可用于获取score
数组中所有元素的总和,最外面的{{1 }}可用于汇总最里面的reduce()
产生的所有结果:
reduce()
答案 5 :(得分:0)
die = [
{
ofWhat: 6,
score: 6
},
{
ofWhat: 6,
score: 1
},
{
ofWhat: 6,
score: 5
}
]
const total = die.reduce((acc,curr) => acc+curr.score,0)
console.log(total)
答案 6 :(得分:0)
您可以通过将所有die.score
值相加来做到这一点。
已更新为使用数组(在问题更新为使用数组之后)
如果总是只有一个数组项,则只需将每个die.score[0]
值相加即可。
在这里,我们计算出6 + 1 + 5 = 12:
var die = [
{ ofWhat: 6, score: [6] },
{ ofWhat: 6, score: [1] },
{ ofWhat: 6, score: [5] }
]
var total = 0;
this.die.forEach((obj) => {
total += obj.score[0];
});
console.log(total);
或者如果每个数组中可以有多个值,则还需要迭代内部数组。
在这里我们计算6 + 6 + 1 + 5 = 18:
var die = [
{ ofWhat: 6, score: [6, 6] },
{ ofWhat: 6, score: [1] },
{ ofWhat: 6, score: [5] }
]
var total = 0;
this.die.forEach((obj) => {
obj.score.forEach((value) => {
total += value;
});
});
console.log(total);
答案 7 :(得分:0)
您可以使用Map
遍历数组let die = [
{
ofWhat: 6,
score: 6
},
{
ofWhat: 6,
score: 1
},
{
ofWhat: 6,
score: 5
}
],sum=0;
die.forEach(x=> sum += x.score);
console.log(sum)
答案 8 :(得分:0)
您可以尝试以下方法:
this.die.forEach((d) => {
this.total += d.score;
});
答案 9 :(得分:0)
仅使用得分[0]。 “分数”是一个数组。
var die = [
{
ofWhat: 6,
score: [6]
},
{
ofWhat: 6,
score: [1]
},
{
ofWhat: 6,
score: [5]
}
];
total = 0;
this.die.forEach((obj) => {
this.total += obj.score[0];
});
console.log("total score from die array: " + total)