2010-08-29 10 views

risposta

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

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

2

vi consiglio di leggere su JavaScript arrays per imparare tutto ciò. È importante conoscere le basi.

Esempio per l'aggiunta di:

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

È possibile creare un costruttore per un oggetto Point come questo:

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

Ora è possibile creare oggetti Point utilizzando la parola chiave new:

var p = new Point(4.5, 19.0); 

Per creare un array di oggetti Point è sufficiente creare un array e inserire Punto oggetti in esso:

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

Oppure:

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

si utilizza l'operatore . per accedere alle proprietà nell'oggetto Point. Esempio:

alert(a[2].x); 

Oppure:

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

veloce, più efficiente:

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

L'efficienza sarà veramente solo essere evidente in una grande varietà di punti.