Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

storing coordinates in array in javascript

I want to store coordinates into an array in javascript, I am new to javascript and do not have an idea how to do it.

Any help would be appreciated.

like image 897
Sara Avatar asked Aug 11 '11 17:08

Sara


1 Answers

There are a number of ways to store x,y coordinates:

Option 1 (every other index in an array):

function storeCoordinate(x, y, array) {
    array.push(x);
    array.push(y);
}

var coords = [];
storeCoordinate(3, 5, coords);
storeCoordinate(19, 1000, coords);
storeCoordinate(-300, 4578, coords);

coords[0] == 3   // x value (even indexes)
coords[1] == 5   // y value (odd indexes)

// to loop through coordinate values
for (var i = 0; i < coords.length; i+=2) {
    var x = coords[i];
    var y = coords[i+1];
} 

Option 2 (simple object in an array):

function storeCoordinate(xVal, yVal, array) {
    array.push({x: xVal, y: yVal});
}

var coords = [];
storeCoordinate(3, 5, coords);
storeCoordinate(19, 1000, coords);
storeCoordinate(-300, 4578, coords);

coords[0].x == 3   // x value
coords[0].y == 5   // y value

// to loop through coordinate values
for (var i = 0; i < coords.length; i++) {
    var x = coords[i].x;
    var y = coords[i].y;
} 
like image 128
jfriend00 Avatar answered Sep 19 '22 13:09

jfriend00