如何在另一个数组中查找子数组?现有代码存问题求更优解法
includes/indexOf Fail for Nested Arrays, and Cleaner Solutions Great question! Let's start by clarifying why your first snippet returns false/-1—it all comes down to how JavaScript compares reference types like arrays.
When you run a.includes([1, 1]), the [1,1] you pass is a brand new array with its own memory reference. Since includes and indexOf use strict equality (===) under the hood, they only match if the exact same array reference exists in a—not just an array with the same values. That's why your first attempt doesn't work.
Your toString() approach works, but it has big limitations: for example, [1, "2,3"] and [1,2,3] would both convert to "1,2,3", leading to false positives. Let's look at better alternatives:
1. Native, Type-Safe Solution: some() + every()
This is the most reliable vanilla JavaScript method, no string conversion needed. It checks each array in a to see if all its values match the target array:
const a = [[1, 1], [2, 2]]; const target = [1, 1]; // One-liner console.log(a.some(item => item.length === target.length && item.every((val, idx) => val === target[idx]))); // Output: true // Reusable function for repeated use const includesArray = (parentArr, targetArr) => parentArr.some(item => item.length === targetArr.length && item.every((val, i) => val === targetArr[i]) ); console.log(includesArray(a, [1,1])); // true
This works for arrays of primitive values (numbers, strings, booleans) and avoids the edge cases of string conversion.
2. JSON Stringify (For Simple, Serializable Data)
If you're certain your arrays only contain JSON-serializable values (no functions, Symbol, undefined, or circular references), you can use JSON.stringify as a simpler shortcut:
console.log(a.some(item => JSON.stringify(item) === JSON.stringify([1,1]))); // Output: true
Just keep in mind: this will fail if your arrays have non-serializable values (e.g., [1, () => {}]), so use it only when you know your data structure is safe.
Why These Are Better Than Your toString() Approach
- No false positives: Unlike
toString(),some()+every()andJSON.stringifyhandle arrays with commas in strings or mixed types correctly. - Better performance: String conversion adds overhead, especially with large arrays or frequent checks. The
some()+every()approach stops as soon as it finds a match, making it faster in most cases.
内容的提问来源于stack exchange,提问作者Vincent

