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

如何在JavaScript中比较URL与列表嵌套对象的href属性?

问题修正与实现方案

首先你的数据结构和代码存在几个关键问题,先逐一解决:

1. 修复数据结构的语法错误

你提供的List1有语法缺失(对象未闭合大括号)和中文引号问题,JS无法识别,先改成标准格式:

const List1 = [
  {
    "type": "text",
    "text": "Test text"
  },
  {
    "type": "text",
    "text": "test1",
    "marks": [
      {
        "type": "link",
        "attrs": {
          "href": "test1"
        }
      }
    ]
  },
  {
    "type": "text",
    "text": "test2",
    "marks": [
      {
        "type": "link",
        "attrs": {
          "href": "test2"
        }
      }
    ]
  }
];

2. 原代码的问题点

  • JS区分大小写,变量名I要改成小写i;
  • if条件末尾缺少闭合括号);
  • 不是所有元素都有marks属性(比如第一个文本元素),直接访问marks[0]会触发报错,必须先做存在性判断。

3. 正确的实现方式

方式1:修正后的for循环(适配你的原始写法)
const my_url = "test1"; // 替换成你要对比的目标URL

for (let i = 0; i < List1.length; i++) {
  const currentItem = List1[i];
  // 先判断元素是否包含链接标记
  if (currentItem.marks && currentItem.marks.length > 0) {
    const linkMark = currentItem.marks.find(mark => mark.type === "link");
    if (linkMark && linkMark.attrs.href === my_url) {
      // 找到匹配的href,执行你的业务逻辑
      console.log(`匹配到对应文本:${currentItem.text}`);
      // Do something….
    }
  }
}
方式2:用forEach遍历(更简洁)
const my_url = "test2";

List1.forEach(item => {
  if (!item.marks) return; // 无marks属性直接跳过
  const link = item.marks.find(m => m.type === "link");
  if (link && link.attrs.href === my_url) {
    console.log(`找到匹配项:${item.text}`);
    // 执行你的操作
  }
});
方式3:用filter筛选所有匹配项

如果需要一次性获取所有href匹配的元素,可使用filter:

const my_url = "test1";
const matchedItems = List1.filter(item => {
  if (!item.marks) return false;
  const link = item.marks.find(m => m.type === "link");
  return link && link.attrs.href === my_url;
});

console.log(matchedItems); // 输出所有符合条件的元素
// 后续可遍历matchedItems执行操作

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 22:35:33