Javascript - 存储大数据集坐标的有效方法(能够按值搜索)?

时间:2017-08-13 11:41:41

标签: javascript arrays coordinates

我有二维坐标,例如(0, 1), (0, 2)(2, 3)等等。起初我想简单地使用像[[0, 1], [0, 2], [2, 3]]这样的数组。但是当我需要按值查找坐标时,我遇到了问题。

我可以实现对数组数组的搜索,但是我需要遍历所有项目以检查匹配(更糟糕的情况)。

例如,如果我需要查找0, 2坐标,我就无法使用arr.indexOf(value),因为value是一个数组。然后我想简单地将坐标存储为arr.push('01')等字符串。

但是我需要使用这些坐标进行计算。所以我需要将其转换为整数,计算然后将其转换回来。

是否有更好的方法可以在不牺牲数据本身的情况下(例如将其转换为字符串)进行高效查找?

3 个答案:

答案 0 :(得分:1)

我会将数据存储在一维数组中。甚至是点的x值的指数,y值的奇数指数。使用以下函数,您可以获得点(x,y)的索引,或获取某个索引处的点的x和y值:

var points = [
//x, y
  0, 1, 
  0, 2, 
  2, 3
];

var findIndexOf = function (x, y) {
  return Math.round(
    points.findIndex((el, i) => i % 2 === 0 && el === x && points[i + 1] === y) / 2
  );
};

var getXValueFromIndex = function (index) {
  return points[index * 2];
};

var getYValueFromIndex = function (index) {
  return points[index * 2 + 1];
};

var index = findIndexOf(0, 2); // the index of (0, 2) in the array
console.log(index); // (0, 2) is the second point in the points array

var x = getXValueFromIndex(index);
var y = getYValueFromIndex(index);
console.log(x, y); // logs (0, 2)

这样,您就不必为每个点创建一个数组。

答案 1 :(得分:0)

如果坐标存在,您可以使用嵌套对象进行快速循环



function check([x, y]) {
    return (x in coords) && (y in coords[x]);
}

var data = [[0, 1], [0, 2], [2, 3]],
    coords = Object.create(null);

data.forEach(([x, y]) => {
    coords[x] = coords[x] || Object.create(null);
    coords[x][y] = true;                          // or any other needed value
});

console.log(check([0, 2]));
console.log(check([0, 0]));
console.log(coords);

.as-console-wrapper { max-height: 100% !important; top: 0; }




答案 2 :(得分:0)

您可以根据坐标创建一个具有属性的对象,如下所示:

var coords = [[0, 2], [0, 1], [3, 2]];
var obj = {};

var setCoord = function (coord, value) {
  obj["c" + coord[0] + coord[1]] = { coord: coord, value: value};
};

var getCoord = function (coord) {
  return obj["c" + coord[0] + coord[1]];
};

setCoord(coords[0], "First coord");
setCoord(coords[1], "Second coord");
setCoord(coords[2], "Third coord");

var someCoord = getCoord(coords[2]);
document.body.innerHTML = `Coordinate: ${someCoord.coord}, Value: ${someCoord.value}`;

这样,您就不必遍历每个坐标,并且可以根据需要将尽可能多的数据链接到坐标。