【问题标题】:Eloquent Javascript Chapter 5 - JSON - Filtering, mapping (Higher-Order functions)Eloquent Javascript 第 5 章 - JSON - 过滤、映射(高阶函数)
【发布时间】: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


    【解决方案1】:

    好的,找到答案了。

    如果其他人对此有疑问,请参见下文...

    过滤器函数有 2 个参数:一个数组和一个测试函数

    本例中的 test 函数为:

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

    在'filter'函数中,我们得到这一行:

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

    所以基本上我们得到了:

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

    因此,无名函数中的 'person' 参数在实际从其 'filter' 父函数中被调用的那一刻被传递。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-23
      • 1970-01-01
      相关资源
      最近更新 更多