简体   繁体   English

雄辩的Javascript第5章-JSON-过滤,映射(高阶函数)

[英]Eloquent Javascript Chapter 5 - JSON - Filtering, mapping (Higher-Order functions)

While explaining array filtering, by using a custom function, I'm having difficulty understanding part of the code (I'll list the function and how it's called below): 在解释数组过滤时,通过使用自定义函数,我很难理解部分代码(我将在下面列出该函数及其调用方式):

The specific line I have trouble with is the calling of the function: 我遇到麻烦的特定行是该函数的调用:

console.log(filter(JSON.parse(ANCESTRY_FILE), function(person) { return person.born > 1900 && person.born < 1925; }))

Specifically, function( person ) {... Where does the argument person come from ? 具体来说,function( person ){...自变量person来自何处? The code works fine, but up to this point I've never declared a function which takes an argument, but then is never passed that argument when it is called. 该代码可以正常工作,但是到目前为止,我还没有声明过一个带有参数的函数,但是在调用它时再也不会传递该参数。 Can someone explain this? 有人可以解释吗?

Worth mentioning is that we are filtering from a JSON object, which should be clear from the JSON.parse function used to extract data into an array. 值得一提的是,我们正在从JSON对象进行过滤,这从用于将数据提取到数组中的JSON.parse函数中应该很清楚。 I've searched the JSON document and there is no mention of an entity or property by the name of 'person' there. 我已经搜索了JSON文档,并且那里没有提及“人”的名称的实体或属性。

以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; }))

Ok found the answer. 确定找到了答案。

In case anyone else has a problem with understanding this, see below... 如果其他人对此有疑问,请参阅下文...

The filter function takes 2 arguments : an array, and a test function . filter函数接受两个参数 :一个数组和一个test函数

The test function in this case being: 在这种情况下, 测试功能为:

function(person) { return person.born > 1900 && person.born < 1925; }

In the ' filter ' function, we get this line: 在“ 过滤器 ”功能中,我们得到以下代码行:

if (test(arr[i])) {...

so basically we're getting: 所以基本上我们得到:

if (arr[i].born > 1900 && arr[i].born < 1925) {..

So the ' person ' argument in the nameless function is being passed the moment the function is actually being called from within its ' filter ' parent function. 因此,实际上是在其“ 过滤器 ”父函数中调用该函数时,便传递了无名函数中的“ ”参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM