javascript - 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语句是解决此类问题的好方法吗?
任何反馈将不胜感激!
解决方案
您可以创建一个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)
推荐阅读
- flutter - 参数类型“BoxShadow”不能分配给参数类型“列表”
' - c# - 详细视图给出错误对象引用未设置为 asp.net mvc 中的对象?
- javascript - javascript fetch 永远不会到达 nodejs 服务器上的 POST 请求
- c++ - 快速字符串解析器 C++
- c++ - CreateDepthStencilView() 失败
- ruby-on-rails - Rails 在删除父项时将子关联 ID 设置为 nil
- java - 即使返回的 ArrayList 不为空,广度优先搜索也会返回空异常指针
- python - 如何在多次运行代码时创建一个 SQLlite 行而不添加另一个相同的行?
- php - 在 Wordpress 子主题中排队多个样式表
- node.js - Nodejs将mongoDB连接对象传递给控制器