javascript - 如何将表格单元格位置计算为数组?
问题描述
我有一张桌子。每个单元格按 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 });
解决方案
我建议您计算行数,然后使用 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);
推荐阅读
- sql - ORA-01810: 格式代码在 SQL 中出现两次
- arm - Cortex-A8 乱序执行和 Spectre
- python - 为什么 numpy 会保留这么多未使用的内存?
- macos - 全新安装monogame,如何解决警告
- performance - 如何在没有循环且时间复杂度较低的情况下从数组列表中删除一些项目?
- angular - Webpack 已使用与 API 模式未知属性“优化”不匹配的配置对象进行初始化
- android - 警报管理器无法在android中的确切时间启动
- python - 使用 crontab 在启动时运行 http.server
- unity3d - 我想在单击按钮时禁用 DetectedPlanes 的 MeshRenderer。我正在使用 ARCore 示例项目
- css - 表行(:after)中的绝对定位元素不滚动