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

如何在JS中检测字符串含指定单词?匹配逻辑问题求助

问题修复:检测字符串包含指定单词并添加请求头

你的代码逻辑搞反了,当前用的tag.includes(collectionName)是判断"product"这个短字符串里是否包含"e23product32"这种长字符串,显然不成立。正确的逻辑应该是检查目标字符串collectionName里是否包含指定的单词tag。

修正后的代码如下:

const productTags = [
  "product"
];

const collectionName = 'e23product32';

const headers = {
  ...(productTags.some((tag) => collectionName.includes(tag)) && {
    "newProduct": "yes",
  }),
};

console.log(headers); // 输出: { newProduct: 'yes' }

说明:

  • 把判断条件从tag.includes(collectionName)改成collectionName.includes(tag),就能正确识别collectionName中是否包含"product"单词。
  • productTags.some()会遍历数组,只要有一个标签满足包含条件,就返回true,进而触发添加newProduct请求头的逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 06:58:23