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

Cocos Creator 3.8中嵌套数组使用indexOf返回-1的问题咨询

问题原因

在JavaScript/TypeScript中,数组属于引用类型,indexOf方法使用严格相等运算符(===)进行匹配。你调用foo.indexOf([0, 0])时,传入的[0, 0]是一个全新的数组对象,和foo中第一个数组[0, 0]并非同一个内存引用,因此无法匹配,返回-1。

解决方法

方法1:保存目标数组的引用

如果可以提前定义目标数组并复用其引用,直接用indexOf就能得到正确结果:

const target = [0, 0];
const foo = [target, [3, 2]];
console.log(foo.indexOf(target)); // 输出 0

方法2:使用findIndex自定义比较逻辑

如果无法提前保存引用,用findIndex遍历数组,自定义数组元素的比较规则:

const foo = [[0, 0], [3, 2]];
// 针对长度为2的数组做精确匹配
const index = foo.findIndex(item => item.length === 2 && item[0] === 0 && item[1] === 0);
console.log(index); // 输出 0

如果需要通用的数组比较,可以封装工具函数:

function arraysEqual(a: number[], b: number[]): boolean {
  if (a.length !== b.length) return false;
  for (let i = 0; i < a.length; i++) {
    if (a[i] !== b[i]) return false;
  }
  return true;
}

const foo = [[0, 0], [3, 2]];
const index = foo.findIndex(item => arraysEqual(item, [0, 0]));
console.log(index); // 输出 0

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 00:39:51