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

如何判断无序且不等长列表中的元素是否存在?现有代码失效

解决方案

核心思路

放弃按索引顺序硬匹配的逻辑,先把其中一组元素的内容提取为可快速查询的集合,再遍历另一组元素做存在性检查——这样不管元素顺序、列表长度差异都能正常生效。

优化后的代码

// 一次性获取所有目标DOM元素,避免重复查询DOM浪费性能
const datenames = document.querySelectorAll('.datename');
const inputnames = document.querySelectorAll('.inputname');
const others = document.querySelectorAll('.other');

// 把datename的文本内容提取到Set中,利用Set的O(1)查找效率提升性能
const datenameContents = new Set(Array.from(datenames).map(el => el.innerHTML.trim()));

// 遍历inputname集合,逐个检查值是否存在于datename的内容集合中
Array.from(inputnames).forEach((inputEl, index) => {
  const inputValue = inputEl.value.trim();
  if (datenameContents.has(inputValue)) {
    // 给对应位置的.other元素添加样式类,先做边界检查避免报错
    if (others[index]) {
      others[index].classList.add('active2');
    }
  }
});

关键细节说明

  • 减少DOM查询次数:把querySelectorAll的结果提前存入变量,不要在循环内反复调用,避免重复遍历DOM树。
  • 处理空白干扰:用trim()去除内容前后的空格、换行符,防止因无关空白导致匹配失败。
  • 边界安全检查:判断others[index]是否存在,避免因两个列表长度不一致引发的报错。

反向匹配场景(若需求是datename对应other)

如果需要判断datename的内容是否存在于inputname的输入值中,再给对应other加类,可调整代码为:

const inputValues = new Set(Array.from(inputnames).map(el => el.value.trim()));

Array.from(datenames).forEach((dateEl, index) => {
  const dateContent = dateEl.innerHTML.trim();
  if (inputValues.has(dateContent)) {
    if (others[index]) {
      others[index].classList.add('active2');
    }
  }
});

内容的提问来源于stack exchange,提问作者Sadra Khandan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 17:20:20