功能执行的次数比预期的多 [英] Function executed more times than expected
问题描述
这是一个简短的Angular应用程序:
Here's a short Angular app:
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>
它正确显示字符串 word
两次,但是当我检查控制台时,它会显示执行4次的功能(通过 console.log('1')
)。有什么想法吗?
It correctly displays the string word
two times, but when I check the console, it shows function executed 4 times (via console.log('1')
). Any idea on why?
推荐答案
这是因为 for..in
属性上的循环和Array也具有属性 length
,另一个使其循环另一次。如果你想看到它只是 console.log(i)
This is because for..in
loops on properties and Array have the property length
too and another one that make it loop another time. IUf you want to see it just do console.log(i)
使用 angular.forEach
或旧的 for(var i = 0; i< ...)
编辑:答案失败:原因是因为角度。
EDIT : failed answer : The reason is because of angular.
他将通过列表两次:一次在初始化,一次在结束时他的循环检查变化
He will go through the list twice : once at init and once at the end of his loop to check for changes
这篇关于功能执行的次数比预期的多的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!