本文介绍了JavaScript:如何检查数组中5个项目中有4个是否完全相同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

美好的一天,

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

I am trying to create a dice poker browser game. The problem that I am having is that I can't seem to figure out how to check the results after a round efficiently.

到目前为止,我想出了一个switch语句,该语句检查是否存在五种"情况.如果是这样,请返回某些内容,否则请继续.

So far I have come up with a switch statement which checks if there is a case of "five of a kind". If so, return something, if not continue.

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种)

What would be an efficient way of checking if exactly 4 out of 5 items in the array are the same?(4 of a kind)

此外,switch语句是解决此类问题的好方法吗?

Also, is a switch statement a good way to solve a problem like this?

任何反馈将不胜感激!

推荐答案

您可以创建一个 counter 对象,该对象将每个 randomNum 作为键及其次数显示为值.然后,使用counter 的值是否为4"rel =" nofollow noreferrer> Object.values() 包含

You could create a counter object which will have each randomNum as key and the number of times it appears as value. Then, check if the counter has 4 as value using Object.values() and 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个是否完全相同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 19:11
查看更多