user9263921
user9263921

Reputation: 3

access object variable within array javascript

I have an array that holds 'particle' objects, with each particle taking parameters; x position, y position, angle of projection, and velocity.

I am trying to access the x and y positions for each particle within the array to perform further calculations, but I am having trouble with the syntax. Here is a brief summary of the code:

var Particle( x, y , angle, velocity) {            
// here the implementation of the dynamics of the particles are coded 
}
     
// here 100 random particle objects 
// are pushed to the array
   var particleArray = [];
    
for(var i =0; i < 100; i++){

particleArray.push(new Particle( 
               (Math.random()* ( innerWidth  - radius*2) + radius), 
               (Math.random()* ( innerHeight - radius*2) + radius), 
               Math.PI*Math.random(), 5 ))      
}

now I want to try and access one of the components , for example: the x position of the 47th particle in the array, but I am having trouble like I said above with the syntax or if I have even approached this problem correctly.

Upvotes: 0

Views: 62

Answers (3)

Andam
Andam

Reputation: 2167

Here is a simple example.

Note that array in javascript are zero based index (first position is zero not one) hence 47th is index 46

var particles = [];
var innerWidth = 10;
var innerHeight = 5;
var radius = 2;

function Particle(x, y, angle, velocity){
  this.x = x;
  this.y = y;
  this.angle = angle;
  this.velocity = velocity;
}

function generateParticles(numberOfParticles){
  var tempParticles = [];
  for(var i = 0; i < numberOfParticles; i++){
    tempParticles.push(
      new Particle( 
          ( Math.random() * (innerWidth - radius * 2) + radius) ,
          ( Math.random() * ( innerHeight - radius * 2) + radius) ,
          Math.PI*Math.random(),
          5 
        )
      );
  }
  return tempParticles;
}

particles = generateParticles(100);
console.log(particles[46])

Upvotes: 0

GregX999
GregX999

Reputation: 26

You should be able to access the x position 47th particle with particleArray[46].x. (Since arrays are "zero-indexed", the first particle is particleArray[0], the second is particleArray[1], etc.)

Upvotes: 1

TimoStaudinger
TimoStaudinger

Reputation: 42460

You can access the n-th object in the array via the square bracket notation (note that arrays are 0-indexed): [n-1].

Then you can access a certain property via the dot notation: object.property.

var x = particleArray[46].x

Upvotes: 2

Related Questions