【问题标题】:Checking the values of two Arrays using Includes使用包含检查两个数组的值
【发布时间】:2021-06-18 03:23:02
【问题描述】:

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

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

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

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")
  }
}

【问题讨论】:

  • 是否有三个数组,但只检查两个数组
  • 这三个数组只是为了检查两个数组时可能出现的条件。那么检查两个数组的最佳解决方案是什么
  • 给我一分钟,我将尝试创建一个最小的可重现示例
  • 您可以按照此处所述的方式使用Array.prototype.every()stackoverflow.com/a/36989813/2610061

标签: javascript arrays include


【解决方案1】:

如果我没记错的话,你要检查数组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() 方法测试数组中的所有元素是否通过 由提供的函数实现的测试。它返回一个布尔值。

【讨论】:

  • 是的,z include y: true。我刚刚又加了一张支票。请看一下@RanjanRajShrestha
猜你喜欢
  • 2021-01-03
  • 2019-10-03
  • 2021-06-06
  • 2015-01-22
  • 2021-08-03
  • 2019-08-10
  • 2014-09-04
  • 1970-01-01
  • 2012-06-13
相关资源
最近更新 更多