多维数组出现意外的indexOf行为

时间:2019-06-12 21:14:31

标签: javascript multidimensional-array indexof

我正在尝试在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似乎是一个问题。有什么解决方案?

2 个答案:

答案 0 :(得分:0)

indexOf使用相等性检查来找到索引,然后

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

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

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

答案 1 :(得分:0)

基本上,您拥有以下数据,并且想要查看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)