如何检测数组中是否包含子数组?JavaScript实现方案咨询
Oh right, this is a classic JavaScript gotcha! When you use indexOf to look for an array inside another array, it checks for exact memory references—not matching content. That’s why ['>', 'PSF', 10] !== ['>', 'PSF', 10] under the hood, even though they look identical. Let’s walk through a few reliable ways to solve this:
1. Use findIndex with a Custom Equality Check
This is the most robust approach, especially if you might have nested arrays or need precise control over what counts as "equal." First, make a helper function to compare two arrays:
function arraysAreEqual(arrA, arrB) { // If lengths don't match, they can't be equal if (arrA.length !== arrB.length) return false; // Loop through each element to compare for (let i = 0; i < arrA.length; i++) { // Recursively check nested arrays if (Array.isArray(arrA[i]) && Array.isArray(arrB[i])) { if (!arraysAreEqual(arrA[i], arrB[i])) return false; } // Strict equality check for primitive values else if (arrA[i] !== arrB[i]) { return false; } } return true; }
Then use it with findIndex to get the index of your target subarray:
let arr = ["all", ['>', 'PSF', 10]]; let segment = ['>', 'PSF', 10]; const targetIndex = arr.findIndex(item => arraysAreEqual(item, segment)); // targetIndex will be 1, just like you expected!
2. Quick-and-Dirty String Conversion (For Simple Cases)
If your arrays only contain primitive values (strings, numbers, booleans) and no characters that would break string serialization (like commas or quotes), you can use JSON.stringify to compare array content:
let arr = ["all", ['>', 'PSF', 10]]; let segment = ['>', 'PSF', 10]; const targetIndex = arr.findIndex(item => JSON.stringify(item) === JSON.stringify(segment)); // Also returns 1 here
Heads up though: This has limitations! For example, JSON.stringify(["a,b", "c"]) matches JSON.stringify(["a", "b,c"]), even though the arrays are different. It also fails with non-serializable values like functions, undefined, or Symbols. Use this only when you’re sure your array contents play nice with JSON.
3. Check for Existence (Not Index) with some
If you don’t need the exact index and just want to know if the subarray exists, some is a cleaner option with the same helper function:
const segmentExists = arr.some(item => arraysAreEqual(item, segment)); // segmentExists will be true
Pick the method that fits your use case—for most scenarios, the custom equality check with findIndex is the safest bet.
内容的提问来源于stack exchange,提问作者yoursweater

