10

我想使用 Javascript 的 array.filter 从数组中删除项目,因为语法优雅且可读。但是,过滤器似乎没有修改原始数组,它只是返回一个新数组,按照您的要求进行过滤。我的问题是,为什么以下工作没有按我的预期工作?

$scope.clearList = function () {
  this.list = this.list.filter(function (item) {
    return item.checked == true;
  });

  //...
}

我希望在返回新过滤的数组后, this.list 现在将只保存过滤后的集合。然而,它不是这样工作的。this.list 最终包含完全相同的项目。更改代码以将过滤后的数组保存在中间变量中表明它确实过滤正确。

我现在已经做了一个解决方法,循环通过过滤的版本并将项目从应该过滤的原始列表中拼接出来,但这并不优雅。我只是想错了吗?


旁注:我正在使用 Angular.js。我不确定这是否重要,但列表来自以下内容:

  <div class="list" ng-repeat="list in lists">
    <!-- ... -->
    <ul>
      <li ng-repeat="item in list">
        <div>
          <label>
            <input type="checkbox" ng-model="item.checked"/>
            {{item.name}}
          </label>
          <!-- ... -->
        </div>
      </li>
    </ul>
    <button class="btn clear-selected" ng-click="clearList()">
      Remove Selected
    </button>
  </div>

编辑以添加调试信息:我引入了一个临时变量,只是为了查看调试器中发生了什么。

var temp = this.list.filter(function (item) {
  return item.checked == true;
});

this.list = temp;

在执行之前,this.List 有 5 个项目,temp 是未定义的。第一行执行后,this.List 有 5 项,temp 有 2 项。执行完最后一行后,this.List 有 2 项,temp 有 2 项。

但是,此后绑定到 this.list 的 UI 似乎没有更新。所以与过滤器无关的事情似乎正在发生。

4

2 回答 2

5

在角度中,您使用特殊$scope变量修改数据,并且在控制器内部this指向$scope作为执行上下文时,$scope这是首选。

当 UI 没有更新时,通常是因为“模型”(或给定范围的属性)的更改是在角度之外完成的。在这种情况下,需要调用 to $apply。这会通知 Angular 某些内容发生了变化并更新视图。

但是,这似乎不是您的问题。我有一个工作列表,这里的改动很小http://plnkr.co/edit/Cnj0fEHSmi2L8BjNRAf5?p=preview

这是控制器的内容,当您clearList()从 UI 调用时,列表中只剩下选中的项目。

$scope.list = [
  {name: 'one', checked: true},
  {name: 'two', checked: false},
  {name: 'three', checked: true},
  {name: 'four', checked: false}
];

$scope.clearList = function () {
  $scope.list = $scope.list.filter(function(item) {
    return item.checked === true;
  });
};  

现在,我建议将列表传递给 clearListclearList(list)或者更好地使用 Angular 过滤器。

于 2012-12-14T22:06:25.227 回答
4
window.list = [1,2,3,4,5,6];
var clearList = function () {
    this.list = this.list.filter(function (item) { return item % 2 === 0; });
};
clearList();
console.log(window.list);

按预期记录[2, 4, 6],所以我认为您的错误与filter.

您确定要修改this.list的数组与您稍后要检查的数组相同吗?

于 2012-12-14T20:43:00.280 回答