我正在使用 React Redux 构建 Yahtzee。在我的 scores reducer 中,我正在计算是否根据骰子状态为小直线奖励 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;
}
关于javascript - 如何在多个条件下使用 .includes()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71212628/