【问题标题】:Unexpected indexOf behavior with multidimensional array多维数组的意外 indexOf 行为
【发布时间】:2023-03-24 21:40:01
【问题描述】:

我正在尝试在 p5.js 中制作经典的蛇游戏。我有一个蛇对象,我将其主体的位置存储在一个二维数组 this.data 中,其中每个元素存储一个 x 值和一个 y 值(分别在索引 0 和 1 处)。随着蛇的移动,我将新位置推入数组中。

当我试图检测蛇是否撞到自己时遇到了问题。我试图做的是使用 indexOf 测试它的当前位置是否已经在数组中,推理如果新位置是打开的,它只会在数组中出现一次,索引比数组的长度小一。否则,如果该位置已经存在于数组中的其他位置(表明蛇已经撞到自己),它将返回一个小于长度减一的值。

但是,这似乎没有发生。

function Snake()
{
    this.x; //x-coordinate of head
    this.y; //y-coordinate of head
    this.dx; //velocity in x-direction
    this.dy; //velocity in y-direction
    this.length; //length of snake
    this.data; //stores all locations snake occupies
    this.alive = 1; //is the snake alive?

    this.update = function(board)
    {
        if (this.alive)//update head position
        {
            this.x += this.dx;
            this.y += this.dy;

            let tempCoords = [this.x,this.y];
            this.data.push(tempCoords);

            while (this.data.length > this.length) //janky
            {
                this.data = this.data.slice(1);
            }

            if (this.data.indexOf(tempCoords) + 1 != this.data.length) //make sure snake hasn't hit itself
            {
                this.alive = 0;
            }
        }

    }
}

即使蛇与自身相交,最后的 if 语句也总是评估为 false。从我所做的测试来看,这似乎是在多维数组上使用 indexOf 的问题。这个问题有什么解决办法?

【问题讨论】:

  • indexOf()searchElement 与使用严格相等的数组元素进行比较(与=== 或三等号运算符使用的方法相同)。这不适用于比较数组。请注意this.data 包含具有一对值的数组。

标签: javascript multidimensional-array indexof


【解决方案1】:

本质上,您有以下数据,并且您想查看head 中的数据是否等于points 中的任何元素

var points = [[1,1],[1,2],[1,3]]
var head = [1,2]

您可以像这样使用Array.some() 检查数组中的任何匹配项:

var overlap = points.some(p => p[0] === head[0] && p[1] === head[1])

var points = [[1,1],[1,2],[1,3]]
var head = [1,2]

var overlap = points.some(p => p[0] === head[0] && p[1] === head[1])

console.log(overlap)

【讨论】:

    【解决方案2】:

    indexOf 使用相等检查来查找索引,并且

      [0, 0] === [0, 0]
    

    is false,作为对象(数组也是对象),通过引用进行比较(并且您确实有两个不同的数组)。要通过它们的内部值比较它们,您必须手动检查 x 和 ys:

      const collides = this.data.some(coords => coords[0] === this.x && coords[1] === this.y);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-16
      • 1970-01-01
      • 1970-01-01
      • 2014-02-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多