1

I'm trying to create a variable array of objects however when I try to do a for loop it only does the iteration once and then stops.

function generate() {
        works = [];  // Clear array
        console.log(num.value);
        for(i=0; i < num.value; i++) {
            console.log(i);
            var fire = new Firework(cxt);
            works.push(fire);
        }
    }

Where cxt is a html canvas context and num.value is a range.

This will only do one iteration and then stop. Here is the constructor for the firework object.

function Firework(Context, DestX, DestY, Speed, Radius, Color, Scale) {
    // Basic Stuff
    this.stat = 0;  // Status of explosion 0 - 100
    this.speed = Speed || 5;
    this.color = Color || "blue";
    this.radius = Radius || 5;
    this.scale = Scale || 1;

    // Movment Stuff
    this.curX = 0;
    this.curY = 0;
    this.destX = DestX || 100;
    this.destY = DestY || 100;
    this.dX = this.speed * Math.cos(Math.atan((this.destY)/(this.destX)));
    this.dY = this.speed * Math.sin(Math.atan((this.destY)/(this.destX)));

    // Spark Stuff
    this.sparkNum = 100;  // SNumber of sparks per level
    this.sparkLvls = 4;  // Number of levels of sparks
    this.sparkAngle = [];
    this.sparkDist = [];

    // Setup Angles and Distances
    for(i=0; i<this.sparkLvls; i++) {  // 4 Levels of sparks
        this.sparkAngle[i] = [];
        this.sparkDist[i] = new Array(this.sparkNum);
        this.sparkDist[i].fill(i*this.radius);  // Set Distance init to 0

        // Generate angles of sparks randomly
        for(j=0; j<this.sparkNum; j++) {
            this.sparkAngle[i][j] = Math.random()*2*Math.PI;
        }
        this.sparkAngle[i].sort();  // Sort angles for difference calc

        // Store Angles as differences between them
        var temp = [];
        for(j=1; j<this.sparkNum; j++) {
            temp[j] = this.sparkAngle[i][j] - this.sparkAngle[i][j-1];
        }
        this.sparkAngle[i] = temp;
    }

    this.context = Context;
}

Any help would be much appreciated. Thanks ahead of time

1
  • num.value is the current position of a range on an html doc. I also checked t o make sure it is greater than 1 Commented Jan 29, 2017 at 19:25

1 Answer 1

2

You use same variable i (without var is a global variable )

add var within the for loops

for(var i=0; i < num.value; i++) { // in  generate function

for(var i=0; i<this.sparkLvls; i++) {  // in Firework function
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.