gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 03:53:08 26 4
gpt4 key购买 nike

我想使用 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项。

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

最佳答案

在 Angular 中,您使用特殊的 $scope 变量修改数据,而在您的 Controller 中,this 指向 $scope 作为执行context,$scope 是首选。

当 UI 不更新时,通常是因为“模型”(或给定范围的属性)的更改是在 Angular 之外完成的。在这种情况下,需要调用 $apply。这会通知 Angular 某些内容已更改并更新 View 。

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

这是 Controller 的内容,当您从 UI 调用 clearList() 时,列表中只会留下选中的项目。

$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;
});
};

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

关于javascript - 使用 Javascript Array.Filter 修改原始数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13885866/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com