2010-08-29 13 views

Répondre

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

Démo: http://jsfiddle.net/gjHeV/

2

Je vous suggère de lire à propos JavaScript arrays pour apprendre tout cela. Il est important que vous connaissiez les bases.

Exemple pour ajouter:

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

Vous pouvez créer un constructeur pour un objet Point comme celui-ci:

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

Maintenant, vous pouvez créer des objets Point en utilisant le mot-clé new:

var p = new Point(4.5, 19.0); 

Pour créer un tableau d'objets Point, créez simplement un tableau et placez Point objets: il

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

Ou:

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

Vous utilisez l'opérateur . pour accéder aux propriétés de l'objet Point. Exemple:

alert(a[2].x); 

Ou:

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

plus rapide, plus efficace:

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'efficacité ne sera réellement perceptible dans un tableau très grand nombre de points.