如何创建Points数组?

cou*_*011 10 javascript

如何创建包含x,y的点对象并创建其数组?这样我就可以遍历这些点,动态添加/删除点.

kar*_*m79 21

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});
Run Code Online (Sandbox Code Playgroud)

演示:http://jsfiddle.net/gjHeV/


Guf*_*ffa 12

您可以像这样为Point对象创建构造函数:

function Point(x, y) {
  this.x = x;
  this.y = y;
}
Run Code Online (Sandbox Code Playgroud)

现在,您可以使用new关键字创建Point对象:

var p = new Point(4.5, 19.0);
Run Code Online (Sandbox Code Playgroud)

要创建Point对象数组,只需创建一个数组,并将Point对象放入其中:

var a = [ new Point(1,2), new Point(5,6), new Point(-1,14) ];
Run Code Online (Sandbox Code Playgroud)

要么:

var a = [];
a.push(new Point(1,2));
a.push(new Point(5,6));
a.push(new Point(-1,14));
Run Code Online (Sandbox Code Playgroud)

您可以使用.运算符访问Point对象中的属性.例:

alert(a[2].x);
Run Code Online (Sandbox Code Playgroud)

要么:

var p = a[2];
alert(p.x + ',' + p.y);
Run Code Online (Sandbox Code Playgroud)