首页 > 解决方案 > 获取具有二维坐标的一维项目,一维数组从二维数组的左下角开始

问题描述

在提供 2D 坐标后,如何获得从 2D 数组左下角开始的 1D 项目?

var width = 3; // the 2D array width
var height = 3; // the 2D array height
var arr = [0, 1, 2, 3, 4, 5, 6, 7, 8]; // 1D array

console.log(getIndex(0,2));
console.log(getIndex(1,2));
console.log(getIndex(2,2));
console.log(getIndex(0,1));
console.log(getIndex(1,1));
console.log(getIndex(2,1));
console.log(getIndex(0,0));
console.log(getIndex(1,0));
console.log(getIndex(2,0));

//Desired output: 0 1 2 3 4 5 6 7 8


function getIndex(x, y) {
  return ... ;   // how????????
}

为了说明,这里是上面代码中一维数组的二维数组:

           X
         0---2

   0     6 7 8
Y  |     3 4 5
   2     0 1 2

*二维数组中的数字代表一维索引中的位置。

标签: javascriptarraysmathmultidimensional-array

解决方案


要提供所需的访问权限(使用反向行顺序),您可以使用以下公式:

indx =  (height - 1 - y) * width + x

推荐阅读