[英]Eloquent Javascript Chapter 5 - JSON - Filtering, mapping (Higher-Order functions)
在解释数组过滤时,通过使用自定义函数,我很难理解部分代码(我将在下面列出该函数及其调用方式):
我遇到麻烦的特定行是该函数的调用:
console.log(filter(JSON.parse(ANCESTRY_FILE), function(person) { return person.born > 1900 && person.born < 1925; }))
具体来说,function( person ){...自变量person来自何处? 该代码可以正常工作,但是到目前为止,我还没有声明过一个带有参数的函数,但是在调用它时再也不会传递该参数。 有人可以解释吗?
值得一提的是,我们正在从JSON对象进行过滤,这从用于将数据提取到数组中的JSON.parse函数中应该很清楚。 我已经搜索了JSON文档,并且那里没有提及“人”的名称的实体或属性。
function filter(arr, test) {
//A custom function for filtering data from an array.
var passed = []; //Creating a new array here to keep our function pure.
for (i=0; i<arr.length; i++) { // Populate our new array with results
if (test(arr[i])) { // test = function(person) { return person.born > 1900 && person.born < 1925; }
passed.unshift(arr[i]); // unshift adds an element to the front of the array
}
}
return passed; //return our results.
}
// Where we call on our function and return the result.
console.log(filter(JSON.parse(ANCESTRY_FILE), function(person) { return person.born > 1900 && person.born < 1925; }))
确定找到了答案。
如果其他人对此有疑问,请参阅下文...
filter函数接受两个参数 :一个数组和一个test函数 。
在这种情况下, 测试功能为:
function(person) { return person.born > 1900 && person.born < 1925; }
在“ 过滤器 ”功能中,我们得到以下代码行:
if (test(arr[i])) {...
所以基本上我们得到:
if (arr[i].born > 1900 && arr[i].born < 1925) {..
因此,实际上是在其“ 过滤器 ”父函数中调用该函数时,便传递了无名函数中的“ 人 ”参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.