开发者

How do I create an array of Points?

开发者 https://www.devze.com 2023-01-14 13:27 出处:网络
How to create point object containing x,y a开发者_StackOverflownd creating its array? so that i can loop over those points, add/remove points dynamically.var points = [{x:45, y:64}, {x:56, y:98}, {x:2

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


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/


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


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消