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

关于JavaScript中indexOf是否遵循严格相等的疑问(含下划线字符串匹配场景)

关于JavaScript中indexOf是否遵循严格相等的疑问(含下划线字符串匹配场景)

嘿,我来帮你理清这个困惑~

你这里其实是把**数组的indexOf和字符串的indexOf**搞混了,而且代码逻辑也不是你原本以为的严格相等判断,才导致了看似不符合预期的输出。

核心问题拆解:

  1. 用错了indexOf的类型:你写的beasts[i].indexOf(item.name)里,beasts[i]是字符串(比如'bison_ox'),所以调用的是字符串的indexOf方法——这个方法的作用是查找「参数是否是当前字符串的子串」,只要子串能在当前字符串里找到(不管是开头、中间还是结尾),就会返回它的起始索引,而不是判断两个字符串是否完全相等。
  2. 为什么会匹配到bison和bison_ox:比如当beasts[i]是'bison_ox'时,item.name为'bison'是它的开头子串,所以'bison_ox'.indexOf('bison')会返回0,不等于-1,就触发了你的console.log,这就是那条意外输出的原因。
  3. 数组的indexOf才是严格相等判断:你原本理解的「indexOf用严格相等」是对的,但那是数组的indexOf——比如beasts.indexOf('bison')会返回0,beasts.indexOf('bison_ox')返回3,它是在数组里寻找和目标值完全严格相等(===)的元素。

修正你的需求(严格匹配字符串)

如果你想要判断beasts[i]和item.name是否严格相等,直接用===就行,不需要调用indexOf:

const beasts = ['bison', 'camel', 'duck', 'bison_ox'];

const tmp = [{id: 1, name: 'bison'}, {id: 2, name: 'camel'}, {id: 3, name: 'duck'}, {id: 4, name: 'bison_ox'}]

// 现在只会输出完全匹配的项
for(let i = 0; i< beasts.length; i++) {
  tmp.forEach(item => {
    if(beasts[i] === item.name) { // 替换为严格相等判断
      console.log('index: ' + i + ' item: ' + item.name + ' beast: ' + beasts[i])
    }
  })
}

这个修正后的代码输出就会是你预期的:

index: 0 item: bison beast: bison
index: 1 item: camel beast: camel
index: 2 item: duck beast: duck
index: 3 item: bison_ox beast: bison_ox

备注:内容来源于stack exchange,提问作者p-a

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.14 15:42:57