javascript - 创建对象数组只进行 1 次迭代

标签 javascript arrays loops object

我正在尝试创建对象的可变数组,但是当我尝试执行 for 循环时,它只执行一次迭代然后停止。

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

其中 cxt 是一个 html Canvas 上下文,num.value 是一个范围。

这只会进行一次迭代然后停止。这是烟花对象的构造函数。

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

任何帮助将不胜感激。提前致谢

最佳答案

你使用相同的变量 i (没有 var 是一个全局变量)

在 for 循环中添加 var

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

for(var i=0; i<this.sparkLvls; i++) {  // in Firework function

关于javascript - 创建对象数组只进行 1 次迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41924974/

相关文章:

javascript - 我应该在 JavaScript 中使用大 switch 语句而不会出现性能问题吗?

java - 将使用字节的 java 函数转换为 Kotlin

Guava :迭代 Multimap 的键-> 集合条目的最佳方法?

javascript - 将对象数组转换为对象的最佳方法?

javascript - 如何将嵌套循环转换为递归?

java - 错误地使用for循环

javascript - Chrome 74 打破了 Chrome 扩展的工作

javascript - 如何将下面的字符串链变成字符串插值?

javascript - 提交时停止表单刷新页面

javascript - 当 ng-repeat 上的复选框具有 required 属性时,Angular ng-model 更改为未定义