未捕获的TypeError:无法设置属性' x'未定义的

时间:2015-06-13 14:29:27

标签: javascript

作为我的第一个代码的一部分,我试图用随机生成的圆圈(星星)制作一个数组。

这是发生TypeError的行。

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

我查看了我的代码并定了星星。

$(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();
    }
}
});

剩下的代码很好但是可能有助于在这里查看其他可能出错的地方。

{{1}}

这是我的第一个程序,所以我不完全确定调试过程。提前谢谢。

2 个答案:

答案 0 :(得分:1)

private final Uri uri = MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI; public Cursor getandroidPlaylistcursor(Context context) { ContentResolver resolver = context.getContentResolver(); final String id = MediaStore.Audio.Playlists._ID; final String name = MediaStore.Audio.Playlists.NAME; final String[] columns = { id, name }; return resolver.query(uri, columns, null, null,name + " ASC"); } 数组已定义,但是start对象在那里?您需要明确地创建这些对象:

stars[i]

或更简洁的语法:

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);
    }
}

答案 1 :(得分:1)

function createStars() { for (var i=0; i<=4; i++) { stars[i] = { x: Math.floor(Math.random() * w), y: Math.floor(Math.random() * h) }; } } 已定义但不是星号[0],即您在for循环中访问的元素。

你的循环应该是这样的

stars
相关问题