Javascript 创建对象数组只进行1次迭代
我试图创建一个对象的可变数组,但是当我尝试执行for循环时,它只执行一次迭代,然后停止Javascript 创建对象数组只进行1次迭代,javascript,arrays,loops,object,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);
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);
}
}
函数生成(){
works=[];//清除数组
console.log(num.value);
对于(i=0;i
其中cxt是一个html画布上下文,num.value是一个范围
这将只进行一次迭代,然后停止。这是firework对象的构造函数
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;
}
功能烟花(上下文、DestX、DestY、速度、半径、颜色、比例){
//基本材料
this.stat=0;//爆炸状态0-100
这个。速度=速度| | 5;
this.color=color | | |“blue”;
这个半径=半径| | 5;
this.scale=scale | | 1;
//电影素材
这个.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));
//火花材料
this.sparkNum=100;//每级火花数
this.sparkLvls=4;//火花级别数
this.sparkAngle=[];
this.sparkDist=[];
//设置角度和距离
对于(i=0;i您使用相同的变量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
生成函数中(var i=0;i
for(var i=0;inum.value是html文档上范围的当前位置。我还检查了它以确保它大于1