javascript - 使用包含检查两个数组的值
问题描述
有没有找到两个数组元素的最佳方法?
在下面的这段代码中,我想通过这个如果条件
我想要解决这个问题的最好方法
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")
}
}
解决方案
如果我没记错的话,你想检查数组是否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()
方法测试数组中的所有元素是否通过提供的函数实现的测试。它返回一个布尔值。
推荐阅读
- java - 连接被拒绝后套接字关闭 - 这是正常行为吗?
- ios - SwiftUI View 在嵌入 UIView 时不更新其状态(使用 UIHostingController)
- c# - 执行 DbGeometry 包含操作时出现 SqlNullValueException
- javascript - 如何通过使用 PHP 和 Javascript 获取单选按钮值来计算总数?
- database - Laravel 工厂 - 创建或制作动态
- azure-devops - 在 Azure Devops 上完成拉取请求后,如何自动“git tag -a”?
- javascript - 阅读 prev 道具:渲染过多
- html - 在进入codeigniter的第二行之前,有什么办法可以让第一行成为强制性的?
- ios - NFC CORE iOS:在同一个会话中读取NDEF、修改数据和WriteNDEF
- python-3.x - 如何在谷歌云存储中获取 GS_SECRET_ACCESS_KEY 和 GS_ACCESS_KEY_ID