首页 > 解决方案 > 使用包含检查两个数组的值

问题描述

有没有找到两个数组元素的最佳方法?

在下面的这段代码中,我想通过这个如果条件

我想要解决这个问题的最好方法

const x =["a"]
const y =["a",3]
const z =["a",undefined,3]

for(let i=0;i<5;i++){
  x[1]=i
  console.log(x)
  if(x.includes(y)){
    console.log("i an in")
  }
  if(x.includes(z)){
    console.log("i am in")
  }
}

标签: javascriptarraysinclude

解决方案


如果我没记错的话,你想检查数组是否x包含数组y,反之亦然。

然后你可以使用Array#every&Array#includes如下:

const x =["a"];
const y =["a", 3];
const z =["a", undefined, 3];

const checkInclude = (a, b) => b.every(v1 => a.includes(v1)); // The same as b.every(v1 => a.some(v2 => v1 === v2));

console.log("x include y: " + checkInclude(x, y));
console.log("y include x: " + checkInclude(y, x));
console.log("z include y: " + checkInclude(z, y));


every()方法测试数组中的所有元素是否通过提供的函数实现的测试。它返回一个布尔值。


推荐阅读