Cole Newbie
Cole Newbie

Reputation: 13

Uncaught TypeError: cannot set property 'x' of undefined

As part of my first code I was trying to make an array with randomly generated circles (stars).

This is the line where the TypeError occurs.

stars[i].x = Math.floor(Math.random() * w)

I looked through my code and stars is defined.

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

The rest of the code was fine but it might help to have it here to see what else may have gone wrong.

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


function init() {
    createStars();
    drawStars();
}

init();

function createStars() {
    for (var i=0; i<=4; i++) {
        stars[i].x = Math.floor(Math.random() * w);
        stars[i].y = Math.floor(Math.random() * h);
    }
}

function drawStars() {
    for (var i=0; i <= 4; i++) {
        ctx.beginPath();
        ctx.arc(stars[i].x, stars[i].y, 10, 0, 2 * Math.PI);
        ctx.stroke();
    }
}
});

This is my first program ever so I'm not entirely sure about the debugging process. Thank you in advance.

Upvotes: 1

Views: 3861

Answers (2)

Pierre Inglebert
Pierre Inglebert

Reputation: 3940

stars is defined but not stars[0], the element you access in your for-loop.

Your loop should be like this

for (var i=0; i<=4; i++) {
    stars.push({
      x: Math.floor(Math.random() * w),
      y: Math.floor(Math.random() * h)
    });
}

Upvotes: 1

dfsq
dfsq

Reputation: 193301

start array is defined, but is stars[i] object there? You need to explicetly create those objects:

function createStars() {
    for (var i=0; i<=4; i++) {
        stars[i] = {};
        stars[i].x = Math.floor(Math.random() * w);
        stars[i].y = Math.floor(Math.random() * h);
    }
}

or more concise syntax:

function createStars() {
    for (var i=0; i<=4; i++) {
        stars[i] = {
            x: Math.floor(Math.random() * w),
            y: Math.floor(Math.random() * h)
        };
    }
}

Upvotes: 2

Related Questions