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

如何基于layouthint筛选数组拆分出tab-view-item项及剩余项

你的代码存在的问题

  • 箭头函数声明语法错误,缺少赋值符号=,也没有定义入参接收要判断的链接元素
  • 核心校验逻辑缺失,没有实现判断layouthint属性值的逻辑
  • filter回调内的函数调用语法错误,不需要加panelLink.前缀,直接把当前遍历的元素传入判断函数即可
  • 若需要同时拿到符合、不符合条件的两组数据,调用两次filter会遍历数组两次,更推荐用reduce一次遍历完成拆分

修复后的实现代码

方案1:保留filter写法(适合仅需单个结果集的场景)

// 补全判断函数的入参和校验逻辑
const hasTabItemViewHint = (panelLink: Node) => {
  // 直接比对属性值,属性不存在时会返回false不会报错
  return panelLink.layouthint === "tab-view-item"
}

// 筛选符合条件的项
const filteredPanelTabItems = panel.panelLinks.links.filter<Node>(
  (panelLink) => hasTabItemViewHint(panelLink)
);
// 筛选剩余不符合条件的项
const otherPanelItems = panel.panelLinks.links.filter<Node>(
  (panelLink) => !hasTabItemViewHint(panelLink)
);

方案2:reduce写法(一次遍历拆分两组数据,性能更优)

const [filteredPanelTabItems, otherPanelItems] = panel.panelLinks.links.reduce<[Node[], Node[]]>(
  (acc, curr) => {
    curr.layouthint === "tab-view-item" ? acc[0].push(curr) : acc[1].push(curr)
    return acc
  },
  [[], []] // 初始化结果容器,第一项存符合条件的元素,第二项存剩余元素
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 20:06:03