如何使用JavaScript从Semantic Search中获取caption文本?
如何使用JavaScript从Semantic Search中获取caption文本?
看起来你遇到的问题大概率是因为response.data.results是一个数组,而不是单个对象哦!你在控制台看到的结构应该是数组里的某一项包含了semanticSearch,直接用.semanticSearch去访问数组本身肯定会报错——毕竟数组根本没有这个属性嘛😉
给你几个实用的解决思路:
- 先确认结构:你可以在控制台打印
console.log(response.data.results),看看它是不是数组格式。如果是的话,得先取数组里的具体元素,再去访问嵌套的semanticSearch。 - 安全访问目标文本:推荐用**可选链操作符
?.**来避免中间属性不存在导致的报错,示例代码如下:// 先获取数组中的第一个结果项 const firstResult = response.data.results[0]; // 安全读取caption文本 if (firstResult?.semanticSearch?.captions?.length > 0) { const targetText = firstResult.semanticSearch.captions[0].text; console.log("获取到的caption文本:", targetText); } else { console.log("未找到可用的caption文本"); } - 如果需要提取所有结果里的caption文本,可以遍历数组处理:
const allCaptionTexts = response.data.results .filter(item => item?.semanticSearch?.captions?.length > 0) .map(item => item.semanticSearch.captions[0].text); console.log("所有caption文本:", allCaptionTexts);
备注:内容来源于stack exchange,提问作者Kenneth
相关产品推荐
相关产品推荐

