简体   繁体   English

如何在函数调用中清除所有已完成的任务?

[英]How can I get all completed tasks to clear on function invocation?

I'm working in Angular, and I have checkboxes that switch the Boolean (to signify task completion). 我在Angular工作,我有复选框切换布尔值(表示任务完成)。 I also have two arrays, one that holds a list of objects and another to hold the first key values once completed and cleared. 我还有两个数组,一个用于保存对象列表,另一个用于在完成和清除后保存第一个键值。

$scope.taskList = [{
  complete: false,
  foo: "1",
  bar: "2",
  baz: "3"
}];

$scope.completedTasks = [];

The below function works properly to clear tasks when only one or two are checked; 当只检查一个或两个时,以下功能可以正常清除任务; however, when the number of items checked grows, only a portion of checked items will clear; 但是,当检查的项目数量增加时,只有部分已检查项目会清除; if you keep invoking the function, eventually all tasks will clear, but I can't figure out how to clear the entire list in one fell swoop. 如果你继续调用该函数,最终所有任务都将清除,但我无法弄清楚如何一举清除整个列表。

$scope.clearComplete = function() {
  for (var i = 0; i < $scope.taskList.length; i++) {
    if ($scope.taskList[i].complete == true) {
      $scope.completedTasks.push($scope.taskList[i].foo);
      $scope.taskList.splice(i, 1);
    }
  }
  console.log($scope.completedTasks);
  return $scope.taskList;
};

I'm at a loss for how to correct the logic and am hoping that some fresh eyes will be able to help me out. 我对如何纠正逻辑感到茫然,并希望一些新鲜的眼睛能够帮助我。

For this project, I'm trying to keep dependencies low, without the help of other helper libraries like Underscore and Lodash. 对于这个项目,我试图保持低依赖性,没有Underscore和Lodash等其他帮助库的帮助。

first of all if you are doing taskList.splic then loop backwards. 首先,如果您正在执行taskList.splic则向后循环。 otherwise you can do like this: 否则你可以这样做:

var incompleteTasks = [];
$scope.tasks.forEach(function(task){
    if(task.complete) {
        $scope.completedTasks.push(task.foo);
    } else {
        incompleteTasks.push(task);
    }
});
$scope.tasks = incompleteTasks;

so, you will iterating exactly once to your array, and make it happen with very cleaner approach. 所以,你将只对你的数组进行一次迭代,并以非常清晰的方法实现它。

You don't need any external libraries to use forEach , or filter . 您不需要任何外部库来使用forEachfilter And I would approach it in two steps for readability: 为了便于阅读,我将分两步进行处理:

$scope.clearComplete = function() {

  //push completed tasks to completedTasks
  $scope.taskList.forEach(function(t) {
    if(t.complete) {
      $scope.completedTasks.push(t.foo);
    }
  });

  //then filter the task list
  $scope.taskList = $scope.taskList.filter(function(t) {
    return !t.complete;
  });

  console.log($scope.completedTasks);
  return $scope.taskList;
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM