简体   繁体   English

JavaScript在for循环中创建对象

[英]JavaScript create objects in for-loop

I'm making a canvas game in JavaScript and have some trouble saving the data. 我正在用JavaScript制作canvas游戏,在保存数据时遇到了一些麻烦。 I'm placing images on the canvas with a for-loop and I want to save information for each image in objects. 我使用for循环将图像放置在画布上,并且希望将每个图像的信息保存在对象中。 For each image an object. 对于每个图像一个对象。

function CreateBlocks(){
    for(var i = 0; i <= blocks; i++){
        var img   = new Image();
        img.src   = "/images/Block.png";

        blockObject = {
            x:    x, 
            y:    y, 
            points:  10
         }
         ctx.drawImage(img,x,y);

         x += 100;
         y += 100;
    }
}

Now this obviously overwrites the blockObject everytime it loops. 现在,这显然会在每次循环时覆盖blockObject I tried adding to loop value to the name of the object like block[i]Object or blockObject[i] but that returns syntax errors. 我尝试将循环值添加到对象的名称(例如block[i]ObjectblockObject[i]但这会返回语法错误。

I could just create a single dimension array for each value, but that seems rather messy to me. 我可以为每个值创建一个维数组,但这对我来说似乎很混乱。 How can I create the objects in the loop? 如何在循环中创建对象?

Simply use an array and push the new object each time: 只需使用数组并每次推送新对象:

function CreateBlocks(){
    var arr = [];

    for(var i = 0; i <= blocks; i++){
        var img   = new Image();
        img.src   = "/images/Block.png";

        arr.push({
            x:    x, 
            y:    y, 
            points:  10
         });

         ctx.drawImage(img,x,y);

         x += 100;
         y += 100;
    }
}

If you create a blockObjects array, your second idea, using the blockObject[i] syntax will work: 如果创建一个blockObjects数组,则使用blockObject[i]语法的第二个想法将起作用:

var blockObjects=[];

function CreateBlocks(){
    for(var i = 0; i <= blocks; i++){
        var img   = new Image();
        img.src   = "/images/Block.png";

        blockObjects[i] = {
            x:    x, 
            y:    y, 
            points:  10
        };
        ctx.drawImage(img,x,y);

        x += 100;
        y += 100;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM