【问题标题】:javascript includes to check for multiple values existance [duplicate]javascript包括检查多个值是否存在[重复]
【发布时间】:2020-05-09 05:26:24
【问题描述】:
const colors = ["black", "red", "pink", ];

这是colors 数组。我可以检查其中一个值是否存在于颜色数组中。例如在这里,我想检查颜色数组中是否存在红色。我使用下面的代码。

Const IsRedExist = colors.includes("red"); //returns true

所以我想要一个标志来知道颜色数组中是否存在红色、白色或蓝色。我如何做到这一点?对此有何建议?

【问题讨论】:

  • 另一个带有someevery的数组
  • “想要一个标志”是什么意思?

标签: javascript arrays loops object


【解决方案1】:

所以你有一些和另一个数组。解决方案取决于您实际需要什么。

const colors = ["black", "red", "pink" ]

const checkFor = ["red", "white"]

const hasAll = checkFor.every(color => colors.includes(color))
const hasSome = checkFor.some(color => colors.includes(color))
const included = checkFor.filter(color => colors.includes(color))
const excluded = checkFor.filter(color => !colors.includes(color))
const checks = checkFor.reduce((obj, color) => ({[color]: colors.includes(color), ...obj}), {})

console.log('hasAll', hasAll)
console.log('hasSome', hasSome)
console.log('included', included)
console.log('excluded', excluded)
console.log('checks', checks, checks.red)

【讨论】:

    猜你喜欢
    • 2017-12-15
    • 1970-01-01
    • 2012-12-06
    • 2014-01-20
    • 1970-01-01
    • 2011-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多