且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-11-30 20:01:52

您可以创建一个 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)