代码之家  ›  专栏  ›  技术社区  ›  me-me

JS中的动态网格

  •  0
  • me-me  · 技术社区  · 6 年前

    我建立了一个网格,但它工作不完全正确。看来我数学有点不对劲。

    所以我的输入数据只是下面的一个伪代码数组。但要知道,它由多个反应组件组成,这些对象具有一个名为SPAN的属性,该属性根据对象本身进行更改。

    伪代码数据输入

    array = [
      {child.. span=100}, {child..span=50}, {child.. span=50}, {child.. span=100}, {child..span=100}
    ];
    

    我想创建一个输出与输入跨度值匹配的多维数组。我的意思是,如果跨度为100,那么它应该创建一行,其中包含一列。如果下一个子级范围属性值为50,那么它应该创建一个新行并将该子级添加到其中。如果下面是另一个50,它应该 不创造 新行 而是相反 只需将新孩子添加到 最后一行 等等…

    所以基本上,所有100个跨度都应该在它们自己的行和跨度中。任何50个跨度应在各自的一行中分开。

    Example pseudocode structure:  [ [ {col} ], [ {col}, {col} ], [ {col} ] ]
    

    外数组表示网格,内括号是行,内括号是列。如我前面所说,这种结构根据跨度大小而变化。目前的网格是2 x 2,但这可能会改变。

    网格代码

      const grid = [];
      const size = 2;
      array.forEach((child, index) => {
        const spanPercent = child.props.span;
        const size = 100 / spanPercent;
        const rowIndex = Math.floor(index / size);
        const colIndex = index % size;
        const row = grid[rowIndex] || (grid[rowIndex] = []);
        row[colIndex] = child;
      }); 
    

    上面给了我一个错误的 根据伪代码中的跨度大小输出。

    输出

     [ [ {col}, {col} ], [ {col} ], [ {col} ]
    

    输入不正确。 100 50 50 100 100 根据输入,我的输出应该是

    [ [ {col} ], [ {col}, {col} ], [ {col} ]
    

    任何人都可以帮我纠正数学。或者是写这个的更好的方法。

    1 回复  |  直到 6 年前
        1
  •  0
  •   Patrick Roberts Benjamin Gruenbaum    6 年前

    您可以通过使用 reduce() 跟踪累积值的方法 span 当前行的每个附加 child grid :

    const array = [{ props: { span: 100 } }, { props: { span: 50 } }, { props: { span: 50 } }, { props: { span: 100 } }, { props: { span: 100 } }];
    const grid = []
    const maxSpan = 100
    
    array.reduce((acc, child) => {
      const { span } = child.props
      const total = acc + span
    
      if (total > maxSpan) {
        grid.push([child])
        return span
      } else {
        grid[grid.length - 1].push(child)
        return total
      }
    }, 100); // force reduce() to start a new row with first child
    
    console.log(JSON.stringify(grid));

    你的错误与使用 index 参数 forEach() ,因为该索引与 rowIndex colIndex 在锯齿状的二维数组中。不是每一行都有 size 你的栏目 网格 .