【问题标题】:How to split items into 3 columns by for loop?如何通过for循环将项目分成3列?
【发布时间】:2019-05-14 19:57:28
【问题描述】:

如何通过 for 循环将项目(网格)拆分为容器的 3 列

我的输出与我想要的不正确

       let array = ['a', 'b', 'c', 'd', 'e', 'f', 'g', and more++];

Let say array will display multiple grid. 


       let rowcount = Math.Ceil(array.length / 3)
       for (let i < 1; i < array.length; i++){
        return i++;
       }

Mine output:- have 7 length of array , after rowcount will get
a        b        c
d        e        f        g
Wrong... 


Expected Output:-
a        b        c
d        e        f
g      more     more
more   more     more 
more   more     more
more   more     more
more   more     more
more   more     more
more   more     more
more

我想在每一行中打印 3 个项目,否则到下一行,即使没有 3 个项目(可能只有 1 个或 2 个)。 有人知道解决方案吗?

【问题讨论】:

  • 您只想打印 3 个项目然后转到下一个新行?
  • 欢迎来到 StackOverflow!不幸的是,你的问题有点含糊。您要拆分的数组是什么?什么是预期的输出?三阵?一个 Html 表格?
  • 你的意思非常非常困惑。你的数组是什么样子的?它是多维的还是应该被分块......?请提供您拥有的数据及其外观。当您说列时,我很感激您格式化您的请求,以便在视觉上有意义,但我们不知道您是指页面上的列还是数据中的列?
  • 致:Michael Platt 是的
  • 收件人:zfrisch 添加

标签: javascript angularjs typescript for-loop


【解决方案1】:

您可以使用ng-repeat 执行此操作,并查看$index 的值。这是一个使用一些 CSS 应用 floatclear 来模拟列的示例。 ng-repeat 需要唯一值,所以我使用 track by 以防您的集合没有唯一标识符。

angular.module('app', [])
  .controller('ctrl', function($scope) {
    $scope.items = [];
    for (let i = 65; i < 91; i++) {
      $scope.items.push(String.fromCharCode(i));
    }
  });
.column {
  width: 50px;
  float: left;
  text-align: center;
}

.last {
  clear: left;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
  <table>
    <div ng-repeat="item in items track by $index" class="column" ng-class="{ last: $index % 3 === 0 }">
      {{ item }}
    </div>
  </table>
</div>

【讨论】:

    【解决方案2】:

    这应该削减它:

    let rowCount = 3;
    
    // Build temp array for example 
    let arr = [...Array(100)].map((e, i) => i);
    
    for (let i = 0; i < arr.length; i += rowCount) {
      // Container to hold current row
      let tmp = [];
      for (let k = 0; k < rowCount; k++) {
        if (i + k === 0) {
          tmp.push(arr[i + k]);
        } else {
          tmp.push(arr[i + k] || 'n/a');
        }
      }
      console.log(tmp);
    }

    【讨论】:

    • 谢谢大家,我发现使用 mod 语法会有所帮助,总共 % 3
    猜你喜欢
    • 1970-01-01
    • 2023-03-03
    • 2019-11-25
    • 2020-04-25
    • 2022-11-13
    • 1970-01-01
    • 2017-05-11
    • 2012-05-30
    相关资源
    最近更新 更多