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

TypeScript数组things中如何检查是否存在含指定name的Party子对象?

正确实现方式

直接使用数组的some方法,传入回调函数做属性匹配即可:

// 匹配name为Bob的Party
const included = things.some(thing => thing.party.name === "Bob");

原有写法错误原因

  1. things.includes(party.name.includes("Bob")):includes 方法用于判断数组是否包含某个指定的常量值,你传入的是party.name.includes("Bob")返回的布尔值,相当于在判断things数组里有没有true/false,完全不符合需求。
  2. things.some(party.name("Bob")):some 要求传入的是回调函数,遍历过程中会把当前数组元素作为参数传入回调,你需要在回调内部完成属性对比逻辑,直接写party.name("Bob")既拿不到遍历的当前元素,语法本身也不成立。

通用封装(可选)

如果需要多次调用可以封装为工具函数,还能享受TypeScript的类型校验:

function checkPartyExist(things: Things[], targetName: string): boolean {
  return things.some(thing => thing.party.name === targetName);
}

// 调用示例
const hasBob = checkPartyExist(things, "Bob");

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 03:06:03