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

JavaScript数组includes方法匹配部分元素返回false的原因

问题根因

Array.prototype.includes() 对值做的是严格全等匹配,针对字符串类型会逐位比对字符内容,你代码里用于查找的值和数组中存储的值本身就不是同一个字符串:

  • 存入数组的URL末尾携带锚点片段 #get-started
  • 传入includes的查找值缺失这段后缀,二者长度、内容均存在差异,匹配失败返回false是符合预期的结果。
逻辑验证

运行以下代码可以直观看到差异:

var u = []
u.push("https://cloudinary.com/products/media_optimizer/web-performance-guide#get-started")

// 直接做严格相等判断,结果为false
console.log(u[0] === "https://cloudinary.com/products/media_optimizer/web-performance-guide")
// 长度对比:存入数组的字符串比查找值多12个字符,正好是"#get-started"的长度
console.log(u[0].length, "https://cloudinary.com/products/media_optimizer/web-performance-guide".length)
修复方案

根据实际业务需求选择对应处理方式即可:

  • 若需要精确匹配完整URL(包含锚点):补全查找值的#get-started后缀即可
    u.includes("https://cloudinary.com/products/media_optimizer/web-performance-guide#get-started") // 返回true
    
  • 若需要忽略URL锚点做匹配:先截断URL去掉哈希片段再做比对,不要直接用原字符串匹配
    const searchKey = "https://cloudinary.com/products/media_optimizer/web-performance-guide"
    const isMatch = u.some(url => url.split('#')[0] === searchKey) // 返回true
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 16:06:30