2010-08-29 162 views

回答

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

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

2

我建议你阅读JavaScript arrays学会了这一切。了解基础知识很重要。

添加

例子:

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

您可以创建一个Point对象这样的构造:

var p = new Point(4.5, 19.0); 

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

现在你可以使用new关键字Point对象创建

要创建Point对象的数组,只需创建一个数组,然后将Point在它的对象:

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

或者:

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

您使用.运营商在Point对象访问属性。例如:

alert(a[2].x); 

或者:

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

更快,更高效:

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

效率才会真正成为一个非常大的阵点的明显。