在javascript中存储数组中的坐标

storing coordinates in array in javascript

本文关键字:坐标 数组 存储 javascript      更新时间:2023-09-26

我想在javascript中存储坐标到数组中,我是新的javascript和不知道如何做到这一点。

有多种存储x,y坐标的方法:

选项1(数组中的其他索引):

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

选项2(数组中的简单对象):

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

我们简单点说,我们想要存储coördinates,所以我们有x和y:

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

这就是在javascript中创建对象的方式,它们就像函数一样。使用这个函数,您可以创建坐标。然后你所需要做的就是创建一个数组:

var arr = new Array();
arr.push(new coordinate(10, 0));
arr.push(new coordinate(0, 11));

就是这些

push方法将完成这项工作:

var arr = new Array();

加勒比海盗。Push ({x: x_coordinate, y: y_coordinate});

然后可以使用

访问它们

arr[0].x(给出x坐标)

arr[0].y(给出y坐标)。

希望能有所帮助。

这些答案是不可用的,如果你试图存储一个网格/矩阵,你想通过x,y值访问数据点以后。

var coords = [];
for(y=0; y < rows; y++){
   for(x=0;x<cols; x++){
      if(typeof coords[x] == 'undefined']){
         coords[x] = [];
      }
      coords[x][y] = someValue;
   }
}
//accessible via coords[x][y] later

我看到了一种使用Set存储坐标的方法。通过使用Set,您可以存储唯一的坐标,这可以在某些时候派上用场。

let coords = new Set();
coords.add(x + "," + y)