首页 > 解决方案 > JavaScript:如何检查数组中5个项目中的4个是否相同

问题描述

再会,

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

到目前为止,我已经提出了一个 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语句是解决此类问题的好方法吗?

任何反馈将不胜感激!

标签: javascriptarrays

解决方案


您可以创建一个counter对象,将每个对象randomNum作为键,并将其出现的次数作为值。然后,使用and检查是否counter有 4 作为值Object.values()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)

推荐阅读