首页 > 解决方案 > 如何将表格单元格位置计算为数组?

问题描述

我有一张桌子。每个单元格按 x,y 位置进行防御。例如,第一个单元格从 0,0 开始,依此类推...

我想把这张桌子变成这个数组[x,y,x,y,x,y....]

例如对于这张图片,预期的结果应该是这样的arr

const arr = [0,0,200,0,400,0,0,200,200,200,400,200,0,400,200,400,400,400];

在此处输入图像描述

问题是我只有这些数据可以使用:

const cols = 3;
const tableWidth = 600;
const colHeight = 200;
const items = 9;
const cellWidth = tableWidth / cols;

因此,我尝试对所有项目执行一个函数并尝试找出 x 和 y。但我不知道如何做到这一点。

const arr = [];

for (var i = 0; i < items; i++) {

  const even = i % 2 === 0;

  const x = ???;
  const y = i * colHeight;

  table.push(x,y);
}

console.log({ arr });

标签: javascript

解决方案


我建议您计算行数,然后使用 2 个循环遍历行和列for- 这将更具可读性:

const cols = 3;
const tableWidth = 600;
const colHeight = 200;
const items = 9;

const cellWidth = tableWidth / cols;
const rows = items / cols;

const arr = [];

for (let i = 0; i < rows; i++) {
  for (let j = 0; j < cols; j++) {
    const x = j * cellWidth;
    const y = i * colHeight;
    arr.push(x, y);
  }
}

console.log(arr);

更新:如果您仍然想要一个for循环,请尝试以下方法:

const cols = 3;
const tableWidth = 600;
const colHeight = 200;
const items = 9;

const cellWidth = tableWidth / cols;

const arr = [];

for (let i = 0; i < items; i++) {
  const col = i % cols;
  const row = Math.floor(i * cols / items);
  arr.push(col * cellWidth, row * colHeight);
}

console.log(arr);


推荐阅读