Javascript日期有两个不同的值,具体取决于它打印的上下文

时间:2015-01-07 08:53:30

标签: javascript angularjs

我看到一些奇怪的事情,Date对象在作为对象的一部分输出时有一个值,与它自己输出时相比。以下代码片段和输出可能最能解释我遇到的问题。特别感兴趣的是$scope.firstDateOfWeek

$scope.month = $scope.month - 1;
$scope.firstDateOfMonth = new Date($scope.year, $scope.month);
$scope.firstDay = $scope.firstDateOfMonth.getDay();
$scope.firstDateOfWeek = new Date($scope.year, $scope.month, 2 - $scope.firstDay);
$scope.lastDate = new Date(new Date($scope.year, $scope.month + 1) - 1);

console.log($scope);
console.log($scope.firstDateOfWeek);
console.log($scope);
console.log($scope.firstDateOfWeek);
console.log($scope);
console.log($scope.firstDateOfWeek);

输出(相同的x 3):

enter image description here

具体来说,当我执行console.log($ scope)时,$ scope.firstDateOfWeek将打印出2015-02-02,但是当我显式打印变量时,console.log($ scope.firstDateOfWeek) ,然后它打印为2014-12-29。

任何人都知道为什么会这样?

编辑:在Hacketo的评论之后,这是代码的其余部分。

var dates = [];

currentDate = $scope.firstDateOfWeek;
for (i = 0;
     (currentDate <= $scope.lastDate ||
     (currentDate > $scope.lastDate && currentDate.getDay() != 1)); i++) {

    if (currentDate.getMonth() == $scope.month) {
        dates.push(new Date(currentDate));

    } else {
        dates.push(null);
    }
    currentDate.setDate(currentDate.getDate() + 1);
}

正在发生的事情是currentDate持有对$ scope.firstDateOfWeek的引用,它在for循环中得到更新。

唯一剩下的问号是console.log()显示的异步行为。有人可以解释一下吗?

0 个答案:

没有答案