简体   繁体   中英

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 ? 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. I've searched the JSON document and there is no mention of an entity or property by the name of 'person' there.

以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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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