Calisto
Calisto

Reputation: 323

JQuery for loop & array - Why is this variable undefined?

I'm following a snake game tutorial. I put 'snake_array.pop()' inside the 'paint()' function for-loop to see what would happen, and I'm trying to understand why I'm getting the following error:

"Uncaught TypeError: Cannot read property 'x' of undefined"

I don't see why 'x' is undefined. The last iteration of the paint() for-loop makes c = snake_array[2], and snake_array[2] is {x:2, y:2}. So why does it state that x is undefined?

$(document).ready(function(){
  
var canvas = $("#canvas")[0];
var ctx = canvas.getContext("2d");
var w = $("#canvas").width();
var h = $("#canvas").height();

ctx.fillStyle = "white";
ctx.fillRect(0, 0, w, h);
ctx.strokStyle = "black";

var snake_array;

create_snake();
function create_snake()
{
  var length = 5;
  snake_array = [];
  for(var i = length - 1;i>=0;i--)
    {
      snake_array.push({x:i,y:2});
    }
}
  
function paint()
{
  
  for(var i=0; i < snake_array.length; i++)
    {
      var tail = snake_array.pop();
 
			var c = snake_array[i];
			ctx.fillStyle = "blue";
			ctx.fillRect(c.x*10, c.y*10, 10, 10);
			ctx.strokeStyle = "white";
			ctx.strokeRect(c.x*10, c.y*10, 10, 10);
      
    }
}
paint();
  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="canvas" width="450" height="450"></canvas>

Upvotes: 1

Views: 480

Answers (1)

hairmot
hairmot

Reputation: 2975

When you set the variable tail, you are removing an element from the array. This array is referenced in the next line: var c = snake_array[i];

This means that for the last iteration of the for loop, c references object at index i in an empty array! Nothing is found, hence the undefined error.

Upvotes: 1

Related Questions