Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/397.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用更新功能,将项目添加到数组中,但它在数组中时会不断更新_Javascript_P5.js - Fatal编程技术网

Javascript 使用更新功能,将项目添加到数组中,但它在数组中时会不断更新

Javascript 使用更新功能,将项目添加到数组中,但它在数组中时会不断更新,javascript,p5.js,Javascript,P5.js,我已经试着修复了大约两个小时了。我尝试过许多不同的方法,但都没能奏效 我正在用JS制作一个蛇游戏(我正在学习),我正在尝试将蛇的位置添加到一个数组中 this.update = function() { for (var i = 0; i < this.length - 1; i++) { this.tail[i + 1] = this.tail[i]; } this.tail[0] = createVector(this.position.x, this.posit

我已经试着修复了大约两个小时了。我尝试过许多不同的方法,但都没能奏效

我正在用JS制作一个蛇游戏(我正在学习),我正在尝试将蛇的位置添加到一个数组中

this.update = function() {
  for (var i = 0; i < this.length - 1; i++) {
    this.tail[i + 1] = this.tail[i];
  }

  this.tail[0] = createVector(this.position.x, this.position.y);

  this.position.x += this.direction.x * 10;
  this.position.y += this.direction.y * 10;

  this.position.x = constrain(this.position.x, 0, width - 10);
  this.position.y = constrain(this.position.y, 0, height - 10);
}
this.update=function(){
对于(var i=0;i
一旦我将一个项目添加到数组中,它将继续更新上一个项目。这真让人讨厌

Imgur已关闭,因此这是一个显示调试信息的图像


我使用的是p5 JS库,这就是我使用“createVector”的原因,但是当我不使用该方法时,问题仍然会发生。

this.tail[I+1]=this.tail[I]让我们做一个例子-您正在更新
this.tail[1]=this.tail[0]。然后下一步,您将执行
this.tail[2]=this.tail[1]
,但在上一步中已将
this.tail[1]
设置为
this.tail[0]
。因此,您正在将所有内容设置为this.tail[0]
。你打算这么做吗?我想你想把一切都向前推进一步,而不是像你那样覆盖一切。哦,这是有道理的。我不是那样想的。我正在尝试将所有内容向前移动一步,以便将数组的第一项设置为新值。请发布一个。请注意,这不应该是您的完整程序,但应该是一个最小的示例,我们可以在自己的机器上复制粘贴来查看问题。多亏了@ASDFGerte,我们成功地解决了这个问题。谢谢