检查数组是否包含另一个数组 JS

如果我有2个数组,就像这样:

arr1 = [[1,2]]
arr2 = [1,2]

如何检查 arr2 是否在 arr1 中?我尝试了以下方法:

arr1.includes(arr2)

但这会返回 false。有没有一种简单的方法可以在JS中做到这一点?

编辑:我还想在arr1中获得arr2的真实索引。例如:

arr1.indexOf(arr2) => 0

因为 arr2 是 arr1 的第一个索引。


撒科打诨
浏览 209回答 3
3回答

慕斯709654

您可以编写一个简单的函数来搜索数组列表,请记住,在比较之前需要这样做。以下是一些示例,可以了解它是否也被发现:arr2sortindexarr2let arr1 = [[1,2]];let arr2 = [1,2];console.log(arrayInList(arr1,arr2));arr2 = [1,3]console.log(arrayInList(arr1,arr2));function arrayInList(arr1, arr2){&nbsp; &nbsp; &nbsp;if(!arr1 || arr1.length==0 || !arr2 || arr2.length==0)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; &nbsp;arr2 = arr2.sort();&nbsp; &nbsp; &nbsp;let foundIndex = -1;&nbsp; &nbsp; &nbsp;for(let i = 0; i < arr1.length; i++){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; let current = arr1[i].sort();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(current.length != arr2.length)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;continue;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; let areEqual = true;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for(let j = 0; j < arr2.length; j++){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if(arr2[j] != current[j]){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; areEqual = false;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(!areEqual){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;continue;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }else{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;foundIndex = i;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;break;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp;return foundIndex;}更快的解决方案是将它们存储在对象中,如下所示:let arr1 = [[1,2]];let arr2 = [1,2];console.log(arrayInList(arr1,arr2));arr2 = [1,3]console.log(arrayInList(arr1,arr2));function arrayInList(arr1, arr2){&nbsp; &nbsp; &nbsp;if(!arr1 || arr1.length==0 || !arr2 || arr2.length==0)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; &nbsp;arr2 = arr2.sort();&nbsp; &nbsp; &nbsp;let set = {};&nbsp; &nbsp; &nbsp;for(let i = 0; i < arr1.length; i++)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; set[arr1[i].sort()] = i;&nbsp; &nbsp; &nbsp;return (set[arr2]!=undefined)?set[arr2]:-1;}

万千封印

为什么不直接使用Array.isArray呢?&nbsp; &nbsp;let arr1 = [[1,2]];&nbsp; &nbsp;let arr2 = [1,2];&nbsp; &nbsp;for (let i = 0; arr1.length; i++) {&nbsp; &nbsp; &nbsp; &nbsp;if (Array.isArray(arr1[i])) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;console.log("Found array!")&nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp;}

幕布斯6054654

你可以做这样的事情:arr1 = [[1,2]]arr2 = [1,2]a = JSON.stringify(arr1);b = JSON.stringify(arr2);并检查索引的值,如果 arr2 不在 arr1 内,它将返回 -1a.indexOf(b);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript