使用Javascript Array.Filter修改原始数组

jth*_*eis 9 javascript arrays filter angularjs

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

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

  //...
}
Run Code Online (Sandbox Code Playgroud)

我希望在返回新过滤的数组后,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>
Run Code Online (Sandbox Code Playgroud)

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

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

this.list = temp;
Run Code Online (Sandbox Code Playgroud)

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

但是,在此之后,似乎绑定到this.list的UI不会更新.所以与过滤器无关的东西似乎正在发生.

jai*_*ime 7

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

当 UI 不更新时,通常是因为“模型”(或给定范围的属性)的更改是在角度之外完成的。$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;
  });
};  
Run Code Online (Sandbox Code Playgroud)

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


Ric*_*ers 5

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);
Run Code Online (Sandbox Code Playgroud)

按预期记录[2, 4, 6],所以我认为无论您的错误是什么,都与filter.

您确定您正在修改的数组与this.list您稍后要检查的数组是同一个数组吗?