You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JavaScript中检查数组是否精确包含另一有序子数组?

检查数组是否包含连续且顺序匹配的子数组(JavaScript实现)

看起来你之前找的方案大多是处理非连续子序列或者仅验证元素存在性,而你需要的是严格连续、顺序完全一致的子数组匹配——这确实是不同的需求,我来给你整理两个实用的实现方式:

核心思路

我们需要遍历父数组的所有可能起始位置,从每个位置开始,检查后续连续N个元素(N是子数组的长度)是否和子数组完全一一对应。一旦找到匹配项就直接返回true,遍历完都没找到则返回false。


方法一:高效双层循环(无额外内存开销)

这个方法适合处理超大数组,因为不会创建新数组,性能最优:

function isContinuousSubarray(parent, child) {
  const childLength = child.length;
  const parentLength = parent.length;

  // 边界情况处理
  if (childLength === 0) return true; // 空数组的返回值可按需调整
  if (childLength > parentLength) return false;

  // 遍历所有可能的起始索引
  for (let i = 0; i <= parentLength - childLength; i++) {
    let isMatch = true;
    // 逐个对比子数组元素
    for (let j = 0; j < childLength; j++) {
      if (parent[i + j] !== child[j]) {
        isMatch = false;
        break; // 不匹配就跳出,节省时间
      }
    }
    if (isMatch) return true;
  }

  return false;
}

方法二:简洁版(利用数组API)

如果你的数组规模不大,用这个写法更简洁,可读性更强:

function isContinuousSubarray(parent, child) {
  const childLength = child.length;
  const parentLength = parent.length;

  if (childLength === 0) return true;
  if (childLength > parentLength) return false;

  for (let i = 0; i <= parentLength - childLength; i++) {
    // 截取父数组对应片段,和子数组逐一对比
    if (parent.slice(i, i + childLength).every((val, idx) => val === child[idx])) {
      return true;
    }
  }

  return false;
}

测试你的示例

// 示例1:匹配成功
const parent1 = ["x", "a", "b", "c", "d", "e", "f", "g"];
const child1 = ["a", "b", "c"];
console.log(isContinuousSubarray(parent1, child1)); // 输出: true

// 示例2:匹配失败
const parent2 = ["x", "g", "b", "c", "d", "e", "f", "a"];
const child2 = ["a", "b", "c"];
console.log(isContinuousSubarray(parent2, child2)); // 输出: false

为什么之前的方案不适用?

你提到的《如何检查数组是否包含另一数组?》这类方案,大多是检查子序列(元素顺序正确但不需要连续),或者仅验证子数组的所有元素都存在于父数组中,完全没考虑「连续」这个核心要求,所以满足不了你的场景。

内容的提问来源于stack exchange,提问作者J Duh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:44:47