【发布时间】:2017-09-17 12:51:46
【问题描述】:
在解释数组过滤时,通过使用自定义函数,我很难理解部分代码(我将在下面列出函数及其调用方式):
我遇到问题的具体行是函数的调用:
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; }))
【问题讨论】:
标签: json function parameter-passing