JavaScript DRY Up代码,避免重复对象键存在检查



嘿,希望一切顺利,

只是结束了一个小的编码任务,我想避免在实现中重复我自己

let matchScores = [
{
'0': { 'Team A': 3, 'Team B': 3 },
'1': { 'Team D': 1, 'Team F': 0 },
'2': { 'Team E': 2, 'Team C': 0 }
},
{
'3': { 'Team E': 1, 'Team F': 2 },
'4': { 'Team B': 0, 'Team D': 0 },
'5': { 'Team C': 4, 'Team A': 2 }
}
]

这是函数的输入,该函数是具有";匹配";两个团队之间的结果。阵列中的每个元素都是不同的";"天";需要附加到总分的游戏的数量。目标是创建一个函数;白天我将遍历数组,并将比赛获胜者的积分相加。

如果一支球队获胜,他们将获得3分,如果平局,两支球队都只获得一分。

预期输出

Match 1
Team A, 3 pts
Team B, 3 pts
Team C, 1 pt
Match 2
Team A, 4 pts
Team B, 3 pts
Team C, 3 pts
function calculateResults(matchDays) {
let matchScore = {};
matchDays.forEach((day, i) => {

for (const [key, value] of Object.entries(day)) {
let match = Object.entries(value);
let team1 = match[0];
let team2 = match[1];
// team 1 win
if (team1[1] > team2[1]) {
// if team's score exists
if (matchScore[team1[0]]) {
// add value
matchScore[team1[0]] += 3;
} else {
// create value
matchScore[team1[0]] = 3;
}
}
// team 2 win
if (team1[1] < team2[1]) {
// if team's score exists
if (matchScore[team2[0]]) {
matchScore[team2[0]] += 3;
} else {
matchScore[team2[0]] = 3;
}
}
// tie
if (team1[1] === team2[1]) {
if (matchScore[team1[0]]) {
matchScore[team1[0]] += 1;
} else {
matchScore[team1[0]] = 1;
}
if (matchScore[team2[0]]) {
matchScore[team2[0]] += 1;
} else {
matchScore[team2[0]] = 1;
}
}
}
});
}

这是我目前的实现。如果对象键值存在,有什么方法可以避免重复检查吗?我目前正在尝试迭代并将值存储在matchScore 中

您可以使用新的(ish(nullish合并运算符将undefined转换为0,然后始终执行加法:

// team 1 win
if (team1[1] > team2[1]) {
matchScore[team1[0]] = matchScore[team1[0]] ?? 0 + 3; // ***
}
// team 2 win
if (team1[1] < team2[1]) {
matchScore[team2[0]] = matchScore[team2[0]] ?? 0 + 3; // ***
}
// ...and so on...

??计算其左侧操作数,如果该值不是undefined,则将该值作为其结果;如果左边的值是undefined,则??计算其右边的操作数,并将该值作为结果。

如果您需要针对一个还没有??的环境,在这种特殊情况下,您可以使用||(逻辑OR(。||执行与??相同的操作,但检查的不仅仅是undefined,而是任何错误值。在这种特殊情况下,这很好。


您可能也想要else ifelse

if (team1[1] > team2[1]) {
// team 1 win
matchScore[team1[0]] = matchScore[team1[0]] ?? 0 + 3;
} else if (team1[1] < team2[1]) {
// team 2 win
matchScore[team2[0]] = matchScore[team2[0]] ?? 0 + 3;
} else {
// tie
matchScore[team1[0]] = matchScore[team1[0]] ?? 0 + 1;
matchScore[team2[0]] = matchScore[team2[0]] ?? 0 + 1;
}

最新更新