对象属性未定义(javascript)

时间:2019-06-17 11:11:14

标签: javascript arrays object undefined

我不明白为什么我的画布没有画出来。 经过一些调试,我发现在第35行,对象“ item”的属性x返回未定义的[canvasContext.fillRect(item.x,item.y,5,5)]。 有人可以解释我为什么?

var players = [];
players.push(new Player(100, 200));
players.push(new Player(300, 200));
players.push(new Player(400, 400));
players.push(new Player(200, 200));

function Player(x, y) {
  this.x = x;
  this.y = y;
}

function auto() {
  setInterval(
    function() {
      movePlayers();
      updateCanvas();
    },
    1000
  );
}

function movePlayers() {
  for (var item in players) {
    item.x += 1;
    item.y += 1;
  }
}

function updateCanvas() {
  var canvas = document.getElementById("canvas");
  var canvasContext = canvas.getContext("2d");
  canvasContext.clearRect(0, 0, canvas.width, canvas.height);
  for (var item in players) {
    canvasContext.fillRect(item.x, item.y, 5, 5);
  }

}
auto()
<canvas id="canvas"></canvas>

1 个答案:

答案 0 :(得分:1)

请不要将for..in用于数组。

players.forEach(item => canvasContext.fillRect(item.x, item.y, 5, 5) )

效果更好

下次再做一个可运行的例子(我的画布太小了)

function Player(x, y) {
  this.x = x;
  this.y = y;
}

function auto() {
  setInterval(
    function() {
      movePlayers();
      updateCanvas();
    },
    1000
  );
}

function movePlayers() {
  for (var item of players) {
    item.x += 1;
    item.y += 1;
  }
}

function updateCanvas() {
  canvasContext.clearRect(0, 0, canvas.width, canvas.height);
  players.forEach(item => canvasContext.fillRect(item.x, item.y, 5, 5) )
}
var canvas = document.getElementById("canvas");
var canvasContext = canvas.getContext("2d");
var players = [new Player(10, 20),
new Player(30, 20),
new Player(40, 40),
new Player(20, 20)
];
auto()
canvas { border:1px solid #d3d3d3; }
<canvas id="canvas"></canvas>