coure2011
coure2011

Reputation: 42444

How do I create an array of Points?

How to create point object containing x,y and creating its array? so that i can loop over those points, add/remove points dynamically.

Upvotes: 13

Views: 38527

Answers (4)

karim79
karim79

Reputation: 342635

var points = [{x:45, y:64}, {x:56, y:98}, {x:23, y:44}];
var len = points.length;
for(var i = 0; i < len; i++) {
    alert(points[i].x + ' ' + points[i].y);               
}
​
// to add more points, push an object to the array:
points.push({x:56, y:87});

Demo: http://jsfiddle.net/gjHeV/

Upvotes: 24

Geuis
Geuis

Reputation: 42277

Faster, more efficient:

var points = [ [45,64], [56,98], [23,44] ];
for(var i=0, len=points.length; i<len; i++){
    //put your code here
    console.log( 'x'+points[i][0], 'y'+points[i][1] )
}
// to add more points, push an array to the array:
points.push([100,100]);

The efficiency will only really be noticeable in a very large array of points.

Upvotes: 0

Guffa
Guffa

Reputation: 700362

You can create a constructor for a Point object like this:

function Point(x, y) {
  this.x = x;
  this.y = y;
}

Now you can create Point objects using the new keyword:

var p = new Point(4.5, 19.0);

To create an array of Point objects you simply create an array, and put Point objects in it:

var a = [ new Point(1,2), new Point(5,6), new Point(-1,14) ];

Or:

var a = [];
a.push(new Point(1,2));
a.push(new Point(5,6));
a.push(new Point(-1,14));

You use the . operator to access the properties in the Point object. Example:

alert(a[2].x);

Or:

var p = a[2];
alert(p.x + ',' + p.y);

Upvotes: 14

Felix Kling
Felix Kling

Reputation: 816462

I suggest you read about JavaScript arrays to learn all that. It is important that you know the basics.

Example for adding:

var points = [];
points.push({x:5, y:3});

Upvotes: 3

Related Questions