【发布时间】:2021-10-05 20:14:30
【问题描述】:
我正在编写一个辅助函数来从数组中获取每个 nth 元素,以便根据列的索引获取特定列的所有表格单元格。
我基于this thread 的回答。
我担心的是,每当我通过列索引 0 时,它都不起作用。 我也不太确定应该将增量更改为什么,因为它不会产生正确的结果。
给定以下数组
const cells = [
'text', 'text', 'text', 'text', 'text', 'text', 'button',
'text', 'text', 'text', 'text', 'text', 'text', 'button',
'text', 'text', 'text', 'text', 'text', 'text', 'button',
];
并通过getColumnCells(cells, 6) 调用该函数,我应该会收到一个“按钮”数组。
const getColumnCells = (cells, columnIndex) => {
const columnCells = [];
const delta = Math.floor(cells.length / columnIndex);
for (let i = columnIndex; i < cells.length; i = i + delta) {
columnCells.push(cells[i]);
}
return columnCells;
};
getColumnCells(cells, 0) 应该返回 ['text', 'text', 'text] 以获取每一行的索引 0。
【问题讨论】:
标签: javascript arrays matrix filter reduce