将项目推送到数组中,仅当今天没有项目符合日期时 - AngularJS

时间:2015-02-21 14:56:47

标签: angularjs

我一直在编写这个非常简单的angularjs函数来查看数组,如果有任何项目的日期与今天的日期相匹配,它就不会将新项目推送到数组中。

我可以看到它有点乱,我觉得可能有一种更简单的方法来实现这一点 - 我知道这不是一个非常明确的问题,但只是喜欢一些指导和提示如何清理这个功能!

当我在循环中移动.push()调用时,我无法将项目推入,我想要实现的是 - 如果数组中有任何项目date今天匹配,我不想推送该项目,而只是打破警报或类似的东西。

感谢您的指导!

$scope.historicalDailyPercentages = [];

$scope.finaliseDay = function(percentComplete) {
        alert("You're finalising this day with a percentage of: " + percentComplete);
        var today = new Date();

      //Confirm that nothing has alreayd been posted for today

      for (var i = $scope.historicalDailyPercentages.length - 1; i >= 0; i--) {

        if($scope.historicalDailyPercentages[i].date == today) {
          console.log("we got a hit!" + $scope.historicalDailyPercentages[i].date);
        }
       else {
           $scope.historicalDailyPercentages.push({percent:percentComplete,  date:today}); //This line doesn't push the item in, but if I include this line at the top of the function, the item is successfully pushed in. 
       }

      };

      console.log($scope.historicalDailyPercentages);



    }

1 个答案:

答案 0 :(得分:1)

您可以使用Array#some()

$scope.finaliseDay = function(percentComplete) {
    alert("You're finalising this day with a percentage of: " + percentComplete);
    var today = new Date();
    var alreadyPresent = $scope.historicalDailyPercentages.some(function (item) { 
        return item.date.getFullYear() === today.getFullYear() &&
               item.date.getMonth() === today.getMonth() &&
               item.date.getDate() === today.getDate();
    });

    //Confirm that nothing has alreayd been posted for today
    if (!alreadyPresent) {
        $scope.historicalDailyPercentages.push({
            percent: percentComplete,
            date: today
        });
    }

    console.log($scope.historicalDailyPercentages);
}