【问题标题】:How to iterate only through defined indexes in array?如何仅通过数组中定义的索引进行迭代?
【发布时间】:2014-01-03 00:32:55
【问题描述】:

我试图只遍历我在 angularjs 的数组中定义的索引,如下所示:

控制器:

$scope.days = new Array();
$scope.days[4] = true;
$scope.days[7] = true;

模板:

<!-- Had to add 'track by $index' to suppress 'Duplicate in a repeater' error-->
<div ng-repeat="(day, value) in days track by $index"> 
    {{day}}: {{value}}
</div>

输出:

0:

1:

2:

3:

4: true

5:

6:

7: true

为什么 ng-repeat '填补空白'索引?我怎样才能让它只打印我明确定义的索引?如果我 console.log out 我的数组,它只会打印我定义的索引。

【问题讨论】:

  • 你不应该使用数组。
  • 它们出现是因为您创建了一个长度为 8 的数组,无论您是否指定了每个索引。您尚未定义的任何索引都是undefined,因此您可以创建一个过滤器或使用ng-if 之类的东西来有条件地显示{{day}}: {{value}}

标签: javascript arrays angularjs angularjs-ng-repeat


【解决方案1】:

用对象字面量替换你的代码:

$scope.days = { 4: true, 7: true }

或者改变你的逻辑并将值放入数组中:

$scope.days = [4,7]

【讨论】:

    猜你喜欢
    • 2018-05-02
    • 1970-01-01
    • 2015-01-21
    • 1970-01-01
    • 2015-03-23
    • 2017-07-21
    • 2023-03-22
    • 1970-01-01
    相关资源
    最近更新 更多