JavaScript (Angular) ForEach循环改变不应用

JavaScript (Angular) ForEach Loop Changes Not Applying

本文关键字:改变 应用 循环 ForEach Angular JavaScript      更新时间:2023-09-26

我有一个对象数组,其日期格式为MMMM Do YYYY格式。我需要将其转换为UNIX时间戳来排列它们,然后将它们转换回可读的日期格式。

然而,在这样做的时候。似乎我从forEach回调内的更改不适用于$scope.lalala变量。

我代码:

    function compare(a, b) {
  if (a.date < b.date)
    return -1;
  if (a.date > b.date)
    return 1;
  return 0;
}
$scope.lalala = arrayofincompleteorders;
$scope.lalala.forEach(function(hiVanilla, index) {
  hiVanilla.date = moment(hiVanilla.date, 'MMMM Do YYYY').format('x');
  if (index == $scope.lalala.length - 1) {
    $scope.lalala.sort(compare); timestamps as expected
    console.log($scope.lalala); //logs the date property with unix 
    callback();
  }
});
console.log($scope.lalala); //logs the date property with unix timestamps, why?
function callback() {
  $scope.lalala.forEach(function(order, index) {
    console.log(order.date); //unix timestamp
    $scope.lalala[index].date = moment(order.date, 'x').format('MMMM Do YYYY');
    console.log($scope.lalala[index].date); //formatted timestamp
  });
};

编辑:我有同样的问题,甚至与角度。回调中的forEach循环:

function callback(){
    angular.forEach($scope.lalala, function(value, key) {
    console.log(value.date);
  value.date = moment(value.date, 'x').format('MMMM Do YYYY');
  console.log($scope.lalala[key].date);
});
  console.log("fire!");
  $scope.apply();
};

我得到的日期改变成功,但然后它说,$scope.apply()不是一个功能,我的脚本的其余部分。

Edit2:

我摆脱了回调,并在一个angular.forEach中拥有一切,但它仍然不适用?

$scope.lalala = arrayofincompleteorders;
 angular.forEach($scope.lalala, function(hiVanilla, key) {
  hiVanilla.date = moment(hiVanilla.date, 'MMMM Do YYYY').format('x');
  if (key == $scope.lalala.length - 1) {
    $scope.lalala.sort(compare); //timestamps as expected
    console.log($scope.lalala); //logs the date property with unix 
    console.log(hiVanilla.date); //unix timestamp
    hiVanilla.date = moment(hiVanilla.date, 'x').format('MMMM Do YYYY');
    console.log($scope.lalala[key].date); //formatted timestamp
  }
});
console.log($scope.lalala); //logs the date property with unix timestamps, why?

看起来我在使用angular.forEach的方式,它不是设计的。

下面的工作,基本上我只是通过将它压入一个空数组来分配它,而不是试图改变我正在循环的数组:

        $scope.lalala=[];
        var log = = arrayofincompleteorders;
        angular.forEach(log, function(value, key) {
        if(value.complete!="TRUE")
        {
        i++;
        value.date = moment(value.date, 'x').format('MMMM Do YYYY');
        this.push(value); //put the new value in $scope.lalala as specified below
        }
        }, $scope.lalala);