检查数组是否包含值或包含另一个值

时间:2021-03-08 19:14:55

标签: javascript arrays include reformatting

const isIncluded = ["1","2"]
        .includes("1") || ["1","2"]
        .includes("2") ;

我怎样才能以更优雅的方式重新格式化这个怪物

2 个答案:

答案 0 :(得分:1)

要检查一个数组与另一个数组,您可以迭代一个数组并使用 includes 检查值。

array.some(v => isIncluded.includes(v))

答案 1 :(得分:1)

你需要这样的东西吗?

const checkIncluded = (arr1, arr2) => arr1.some(item => arr2.includes(item));

如果 arr1 中的任何项目在 arr2 内,则返回 true。

示例:

const isIncluded1 = checkIncluded(["1", "2"], ["1","2"]) // true
const isIncluded2 = checkIncluded(["1", "2"], ["1"]) // true
const isIncluded3 = checkIncluded(["1", "2"], ["2"]) // true
const isIncluded4 = checkIncluded(["1", "2"], ["3", "5"]) // false