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

如何在JavaScript中对比for循环遍历的JSON条目与页面p标签的内容

问题原因

  1. 遍历数组方式错误:你使用for...in遍历数组的逻辑不符合规范,for...in是为遍历对象属性设计的,用于数组时会遍历到原型链上的可枚举属性,极易出现索引异常,你的日志中dept一直停留在第一个值Ain,就是因为循环异常只执行了第一轮。
  2. 字符串匹配有空格误差:DOM中p标签的内容前后带有多余空白字符,直接使用==匹配时,即使名称字面一致也会匹配失败。
  3. 冗余逻辑:序列化再反序列化JSON的操作完全多余,import引入的JSON文件已经是可以直接使用的JS对象;另外双重循环逻辑效率极低,每遍历一个部门就要全量扫描所有DOM元素,完全可以优化为单次遍历。
  4. 注意属性选择器正确性:如果你的DOM中自定义属性是标准的data-interval(而非写死的dataset-interval),需要调整jQuery选择器的属性名。

修复方案

推荐使用更高效的单次遍历方案,代码如下:

import departement_list from "../data/departements-region.json";

// 先构建部门名称映射表,方便后续快速匹配
const deptMap = new Map();
departement_list.forEach(deptItem => {
  deptMap.set(deptItem.dep_name.trim(), deptItem);
});

// 仅遍历一次DOM元素即可完成所有匹配
$(".domtom-container [dataset-interval]").each(function () {
  const $currentDom = $(this);
  // 去除p标签内容前后的空白字符
  const currentPContent = $currentDom.find("p").text().trim();
  
  if (deptMap.has(currentPContent)) {
    const matchedDept = deptMap.get(currentPContent);
    // 此处写匹配成功后的业务逻辑
    console.log("匹配成功:", currentPContent, matchedDept);
  }
});

如果需要保留你原本的双重循环逻辑,只做最小修改的话,可以改成如下版本:

import departement_list from "../data/departements-region.json";

// 用数组的forEach替代for...in遍历
departement_list.forEach(deptItem => {
  $(".domtom-container [dataset-interval]").each(function () {
    const $currentDom = $(this);
    const currentPContent = $currentDom.find("p").text().trim();
    const deptName = deptItem.dep_name.trim();
    console.log("dept = ", deptName);
    console.log("paragraph =  ", currentPContent);
    if (currentPContent === deptName) {
      // 业务逻辑
    }
  });
});

内容的提问来源于stack exchange,提问作者Meryem ACHEMLAL

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 08:45:04