如何在多个条件下使用.includes()



我正在用React Redux构建Yahtzee。在我的减分器中,我根据骰子状态计算是否奖励小直30分。骰子状态表示为一个数组,因此我必须检测这个数组是否包括1、2、3、4。。。2、3、4、5。。。或3、4、5、6。我想出的办法奏效了,但看起来很乱(下图(。有没有一种更干净的方法来检查这些值集是否出现在数组中?

setSmallStraight: (state, action) => {
if (
action.payload.includes(1)
&& action.payload.includes(2)
&& action.payload.includes(3)
&& action.payload.includes(4)
||
action.payload.includes(2)
&& action.payload.includes(3)
&& action.payload.includes(4)
&& action.payload.includes(5)
||
action.payload.includes(3)
&& action.payload.includes(4)
&& action.payload.includes(5)
&& action.payload.includes(6)
) {
state['Small Straight'] = 30
} else {state['Small Straight'] = 0} 
},

您可以使用array.some()array.every()

const small_straights = [
[1, 2, 3, 4],
[2, 3, 4, 5],
[3, 4, 5, 6]
];
if (small_straights.some(dice => dice.every(die => action.payload.includes(die))) {
state['Small Straight'] = 30;
} else {
state['Small Straight'] = 0;
}

使用Array#someArray#everySet:

const _hasAll = (arr = [], nums = []) => {
const set = new Set(arr);
return nums.every(num => set.has(num));
}
const shouldAward = ({ payload = [] }) =>
[[1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 6]].some(nums => _hasAll(payload, nums));

console.log( shouldAward({ payload: [1, 2, 3, 4] }) );
console.log( shouldAward({ payload: [2, 3, 4, 5] }) );
console.log( shouldAward({ payload: [3, 4, 5, 6] }) );
console.log( shouldAward({ payload: [4, 5, 6, 7] }) );

最新更新