<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"> </script>
</head>
<body>
<div ng-app="myApp" ng-controller="personCtrl">{{count()}}</div>
<script>
var app = angular.module('myApp', []);
app.controller('personCtrl', function($scope) {
$scope.listarray=[1,2,3,4];
var count=0
$scope.count = function() {
angular.forEach($scope.listarray,function(value,key){
count=count+1;
});
return count;
}
});
</script>
</body>
</html>
上述代碼顯示的答案是88
。當var count
在裏面時count
功能顯示4
但在count
功能外顯示88
。爲什麼會發生?伯爵的答案是88:爲什麼?
o真的是顯示88?你能告訴我結果在小提琴手嗎? –
http://jsfiddle.net/satpalsingh/0s12zf1k/,只需在函數內定義'var count'即可。 _OR_ YOu可以簡單地使用'listarray.length'像http://jsfiddle.net/satpalsingh/Lc4yvbc9/ – Satpal