[英]How to calc table cell position to array?
我有一张桌子。 每个单元格由 x,y position 保护。 例如,第一个单元格从 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;
因此,我尝试对所有项目进行 function 并尝试找出 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 });
我建议您计算行数,然后使用 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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.