JavaScript从给定宽度和高度的平面数组中确定行、列和元素的相对位置

JavaScript determine rows, columns and element relative position from a flat array given width and height

本文关键字:位置 相对 元素 平面 JavaScript 高度 数组      更新时间:2023-09-26

这是我遇到的一个更复杂问题的简化版本。我把它简化了以便更好地解释。

我有一个单维数组,它代表一个网格,每行3个元素,每列4个元素。我无法将数组转换成多维数组。数组看起来像这样:

var myArray = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l'];

我知道数组的高度和宽度(作为元素的数量):

var width = 3;
var height = 4;

我正在寻找一些方法来迭代数组并确定它所在的任何元素,并将函数应用于同一行中的所有元素。

// do something here to derive the 
// starting index and ending index of the row this element is in
// so I apply a function to only elements in that row
var startOfRow = getStartOfRow(myArray); // 2
var endOfRow = getEndtOfRow(myArray);    // 6
// in this case I need to know i=3 is the start of the row
// and i=5 is the end of the row 
// so i can do this:
for(i=0;i<myArray.length;i++) {
  if(i > startOfRow && i < endOfRow) {
    // affect all elements in the second row
    doStuff(myArray[i]);
  }
};

在循环中,Math.floor(i / 3)将给您行,i % 3将给您列,两个索引都从0开始。

所以尝试……

for(i=0;i<myArray.length;i++) {
  var row = Math.floor(i / 3);
  var col = i % 3;
  // affect all elements in the second row
  if(row==1) {
    doStuff(myArray[i]);
  }
};