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

React中数组含已存在对象时,为何includes方法返回false?

问题原因

你用includes检查对象是否存在于数组里返回false,核心原因是JavaScript中对象属于引用类型。includes方法采用严格相等(===)进行比较,你创建的newNameObject和数组里原有的{ name: 'Arto Hellas' }是两个完全独立的对象——哪怕内容完全一致,它们在内存中的引用地址也不相同,所以===会判定二者不相等,最终导致includes返回false。

解决方法

不要直接用includes对比对象,改用some方法遍历数组,通过对比对象的name属性值来判断是否重复:

修改后的addName函数如下:

function addName(e){
  const newNameObject = {
    name: newName
  }
  e.preventDefault()
  setNewName("") 
  // 检查数组中是否已有同名对象
  const isDuplicate = persons.some(person => person.name === newName)
  if(isDuplicate){
    alert(`${newName} has already been added`)
  } else {
    setPersons(persons.concat(newNameObject))
  }
}

这样就能准确判断输入的名字是否已经存在于数组中,实现你要的去重效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 17:45:49