2014-09-26 139 views
-1

我在示例中有这几行代码。本教程解释了过滤器功能匹配并返回匹配的国家记录。 Where &如何设置entry.name。过滤器功能如何工作?

myApp.controller('detailcontroller', function($scope, $routeParams, $http) { 
    $scope.name=$routeParams.countryname; 
    $http.get('countries.json').success(function(data) { 
    var country =data.filter(function(entry) { 
     return entry.name === $scope.name; 
    }) [0]; 


    console.log(country); 
}); 

}); 
+0

[文件](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter )。 – Blackhole 2014-09-26 14:07:40

+0

'data.filter(...)'方法正在接受一个匿名函数,它可能会调用'data'变量中的每个项目,以确定每个项目是否满足提供的函数中的条件(即该项目的名称等于'$ scope.name'变量)。 – ne1410s 2014-09-26 14:16:02

回答

0

它没有“设置”。您可以为过滤器函数指定一个迭代器(回调函数)。

该文档表示:Function to test each element of the array. Return true to keep the element, false otherwise.

因此,基本上,entry表示数组的一个元素。对于数组中的每个元素,将使用元素作为参数调用您的函数(如果您有一个国家数组,则条目将是第一个国家,然后是第二个国家等)。

这也许是更容易理解你:

var testIfCountryMatches = function(country){ 
    console.log("is "+country+" France ? : "+(country.name === "France")); 
    return country.name === "France"; 
} 

var matchingCountries = data.filter(testIfCountryMatches); 
var fr = matchingCountries[0];