你好,
我正在尝试创建一个骰子扑克浏览器游戏。我遇到的问题是我似乎无法弄清楚如何在一轮后有效地检查结果。
到目前为止,我已经提出了一个 switch 语句来检查是否存在“五种情况”的情况。如果是这样,返回一些东西,如果不是继续。
const getResult = diceArr => {
// Create an array with only the numbers
let dice1 = diceArr[0].randomNum;
let dice2 = diceArr[1].randomNum;
let dice3 = diceArr[2].randomNum;
let dice4 = diceArr[3].randomNum;
let dice5 = diceArr[4].randomNum;
diceArray = [];
diceArray.push(dice1, dice2, dice3, dice4, dice5);
// Check the result using a switch statement. Start at the highest rank. If encountered, stop checking.
let result;
switch(result) {
case diceArray[0] === diceArray[1] === diceArray[2] === diceArray[3] === diceArray[4] :
console.log('5 of a kind!');
break;
// case ? -> No idea where to go from here
}
}
检查数组中 5 个项目中是否恰好有 4 个相同的有效方法是什么?(4 个相同)
此外,switch 语句是解决此类问题的好方法吗?
如有任何反馈,我们将不胜感激!
最佳答案
您可以创建一个 counter
对象,它将每个 randomNum
作为键,并将它出现的次数作为值。然后,使用 Object.values()
检查 counter
的值是否为 4和 includes
const counter = diceArr.reduce((acc, o) => {
acc[o.randomNum] = acc[o.randomNum] + 1 || 1;
return acc
}, {})
const isFourOfAKind = Object.values(counter).includes(4);
console.log(isFourOfAKind)
关于JavaScript:如何检查数组中 5 个项目中是否恰好有 4 个相同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59499992/