函数执行的次数超出预期

Function executed more times than expected

本文关键字:执行 函数      更新时间:2023-09-26

这里有一个简短的Angular应用程序:

angular.module('AppName', [])
.controller('TwoController', function($scope){
var oneArray = ['1','2'];
$scope.secondArray = [];
for (i in oneArray){
  $scope.secondArray.push({
    property: function(){
      console.log('1');
      return 'word';
    }
  })
}
});

在我看来:

<div ng-app="AppName" ng-controller="TwoController">
<p ng-repeat='entry in secondArray'>{{entry.property()}}</p>
</div>

jsfiddle上的例子。

它正确地显示了两次字符串word,但当我检查控制台时,它显示了4次执行的函数(通过console.log('1'))。知道为什么吗?

这是因为属性上的for..in循环和Array也有属性length,还有一个属性使它下次循环。IU如果你想看,就做console.log(i)

使用angular.forEach或旧的for(var i = 0; i < ...)

编辑:失败的答案:原因是因为棱角分明。

他将遍历该列表两次:一次在init,一次在循环结束时检查的更改

看起来视图只渲染了两次,所以我认为您没有真正的问题。。。