JavaScript:如何检查数组中 5 个项目中是否恰好有 4 个相同

标签 javascript arrays

你好,

我正在尝试创建一个骰子扑克浏览器游戏。我遇到的问题是我似乎无法弄清楚如何在一轮后有效地检查结果。

到目前为止,我已经提出了一个 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/

相关文章:

javascript - 检查对象数组中的重复条目并创建一个新条目

javascript - 启用具有自定义布局的数据表

javascript - Express js 路由器不工作

javascript - 查找父节点的索引

java - 类中的全局数组根据传递参数问题初始化大小

iOS:将核心数据提取的结果转换为数组并传递给另一个类

javascript - 创建自定义节点以扩展 HTMLIFrameElement

java.lang.ArrayIndexOutOfBoundsException : 0 (stack implementation) 异常

c - 在 C 中,普通数组和使用 malloc 创建的数组有什么区别?

python - 如何将这个多维列表 reshape 为二维数组?