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

NextJS中TypeScript代码的Array.includes方法未正常工作问题

问题分析:为什么数组includes方法无法匹配目标对象?

你的代码及运行现象

const holeSet:any[] = [];
.....

let xx = 1, yy = 2;
holeSet.push({x:xx,y:yy});

xx = 3;
yy = 4;
holeSet.push({x:xx,y:yy});

holeSet.map((e) => {
  console.log("element ::"+JSON.stringify(e));
});

const a = 1;
const b = 2;

if (holeSet.includes({x:a.toString(),y:b.toString()}))
  console.log("Value {1;2} FOUND !");

运行后控制台输出:

element ::{"x":1,"y":2}
element ::{"x":3,"y":4}

但未出现预期的Value {1;2} FOUND !日志。

原因解析

  1. 对象的引用比较特性:includes方法判断元素是否存在时,对于对象类型是用内存引用地址来比较的。你在includes里新建的{x:a.toString(),y:b.toString()}是一个全新的对象,和数组里的{x:1,y:2}虽然内容一致,但内存地址完全不同,所以includes会返回false。
  2. 类型不匹配问题:数组中存储的对象属性x、y是数字类型(1、2等),但你判断时用toString()转成了字符串类型,就算做值比较,类型不一致也无法匹配成功。

解决方案

方案一:使用some方法自定义值比较逻辑

some方法允许你自定义判断规则,直接比较对象的属性值和类型:

const a = 1;
const b = 2;

if (holeSet.some(item => item.x === a && item.y === b)) {
  console.log("Value {1;2} FOUND !");
}

如果确实需要比较字符串类型的属性值,可以改成:

if (holeSet.some(item => item.x.toString() === a.toString() && item.y.toString() === b.toString())) {
  console.log("Value {1;2} FOUND !");
}

方案二:将对象序列化为字符串存储

如果需要频繁判断对象是否存在,可以在存入数组时把对象转成JSON字符串,判断时也转成相同格式的字符串:

// 存入数组时
holeSet.push(JSON.stringify({x:xx,y:yy}));

// 判断时
const target = JSON.stringify({x:a,y:b});
if (holeSet.includes(target)) {
  console.log("Value {1;2} FOUND !");
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 21:41:20