Reputation: 89
I attempt to push something to my array. But when i use console.log it return an empty array. As a beginner, I am wondering if I did anything wrong?
const canvas = document.getElementById('canvas1')
const ctx = canvas.getContext("2d")
canvas.width = innerWidth
canvas.height = innerHeight
let particlesArray
class Particles {
constructor(x, y, directionX, directionY) {
this.x = x
this.y = y
this.directionX = directionX
this.directionY = directionY
}
draw() {
ctx.beginPath()
ctx.fillStyle = "#c1dfdc"
ctx.arc(this.x, this.y, 20, 0, 2 * Math.PI)
ctx.closePath()
ctx.fill()
}
}
particlesArray = []
//calculate how many particles should render
numberOfParticles = window.innerHeight * window.innerWidth / 9000
function generateParticlesArray() {
for (let i; i < numberOfParticles; i++) {
let x = Math.random()
let y = Math.random()
let directionX = (Math.random() - 0.5) * 8
let directionY = (Math.random() - 0.5) * 8
particlesArray.push(new Particles(x, y, directionX, directionY))
}
console.log(particlesArray)
}
generateParticlesArray()
<canvas id="canvas1"></canvas>
Upvotes: 2
Views: 454
Reputation: 3224
Your mistake is forgetting to initialize your iterator variable i
in the begin part of your for
loop statement:
for (let i; i < numberOfParticles; i++) {
...
Should instead be:
for (let i = 0; i < numberOfParticles; i++) { // notice we declare and initialize i with let i = 0;
...
You can indeed see that the below for loop below will not iterate at all:
const x = 10;
for (let i; i < 10; i++) {
console.log(i);
}
console.log("done");
This is because i
implicitly takes on the value of undefined
if it is declared but not initialized. Numerical comparisons with undefined
cause it to get converted to NaN
, a special numeric value which returns false for all comparisons. See https://javascript.info/comparison#an-incomparable-undefined
Upvotes: 4
Reputation: 178421
You missed a 0 in let i=0;
Also you have too many assignments. Just have one and DRY: Don't repeat yourself:
const canvas = document.getElementById('canvas1'),
ctx = canvas.getContext("2d"),
iW = window.innerWidth,
iH = window.innerHeight,
numberOfParticles = parseInt(iH * iW / 9000); //calculate how many particles should render
canvas.width = iW; canvas.height = iH;
ctx.fillStyle = "grey"; ctx.fillRect(0, 0, canvas.width, canvas.height);
class Particles {
constructor(x, y, directionX, directionY) {
this.x = x; this.y = y;
this.directionX = directionX; this.directionY = directionY;
}
draw() {
ctx.beginPath();
ctx.fillStyle = "#c1dfdc";
ctx.arc(this.x, this.y, 20, 0, 2 * Math.PI);
ctx.closePath();
ctx.fill();
}
};
const generateParticlesArray = numberOfParticles => Array
.from({ length: numberOfParticles })
.map((_, i) => new Particles(Math.random(), Math.random(), (Math.random() - 0.5) * 8, (Math.random() - 0.5) * 8))
let particlesArray = generateParticlesArray(numberOfParticles)
particlesArray.forEach(particle => particle.draw())
<canvas id="canvas1"></canvas>
Upvotes: 0