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

标签 javascript arrays

我正在使用 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/

相关文章:

arrays - 在 swift 5 中过滤结构的嵌套数组

c++ - 访问 Library.cpp 中的数组

javascript - DevExtreme - 尝试从 SQL 将数组分配给 dxList

javascript - 为什么我的 div 元素没有根据我的移动功能移动?

javascript - Webdriver.IO 接收到 : "npm ERR! Test failed. See above for more details." but can't see the errors

javascript - AJAX 调用 - 每次点击闪烁更多

javascript - 正则表达式模式匹配等于 0's and 1' s

php - Codeigniter update_batch增量值

java - 检查数组中的所有值是否不相等 (java)

python - 如何在Python中的随机数数组中找到最多和最少被猜到的数字?