use*_*647 1 javascript arrays loops object
const colors = ["black", "red", "pink", ];
Run Code Online (Sandbox Code Playgroud)
这是colors数组。我可以检查颜色数组中是否存在其中一个值。例如,在这里,我想检查颜色数组中是否存在红色。我使用下面的代码。
Const IsRedExist = colors.includes("red"); //returns true
Run Code Online (Sandbox Code Playgroud)
所以我想要一个标志来知道颜色数组中是否存在红色、白色或蓝色。我该如何实现这一目标?对此有何建议?
所以你有些和每个都有另一个数组。解决方案取决于您的实际需要。
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)Run Code Online (Sandbox Code Playgroud)