【问题标题】:Understanding HOF with default parameter in TypeScript map在 TypeScript 映射中使用默认参数理解 HOF
【发布时间】:2021-09-03 03:33:17
【问题描述】:

我在 JS/TS 映射中使用 HOF。我的函数有一个默认参数。 map 似乎将数组元素转换为函数列表参数。 能不能给我详细解释一下?

我在这里做了几个简单的例子

数组中的单个元素:

function add(a: number, b: number = 1) {
    console.log(b) // 0
    return a + b
}

console.log([1].map(add)) // [1]

数组中的多个元素:

function add(a: number, b: number = 1) {
    console.log(b) // 1,2
    return a+b
}

console.log([1,2,3].map(add)) // [1, 3, 5]

【问题讨论】:

    标签: javascript typescript higher-order-functions


    【解决方案1】:

    JS map function 接收一个回调函数,在该回调中包含三个参数:

    map<U>(callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): U[];
    
    • 正在处理数组中的当前元素。
    • 当前正在处理的元素在数组中的索引。
    • 调用了数组映射

    所以当你把它放在地图函数中时,它就像一个回调函数:

    function add(a: number, b: number = 1) {
        console.log(b) // 0
        return a + b
    }
    

    这在有意义的命名中也意味着:

    function add(currentValue: number, index: number) {
        return currentValue + index;
    }
    

    正如我之前写的,a 是 The current element is being processed in the array,b 是 The index of the current element being processed in the array

    所以你上面的函数是这样的:

    console.log([1].map((a, b) => a + b))
    console.log([1,2,3].map((a, b) => a + b));

    或者这个,用更有意义的参数命名:

    console.log([1].map((currentValue, index) => currentValue + index))
    console.log([1,2,3].map((currentValue, index) => currentValue + index));

    【讨论】:

    • 感谢您的解释。这是有道理的。
    • 如果答案有帮助,您可以考虑投票/标记接受
    【解决方案2】:

    如果你看到地图语法是

    map((element, index, array) => { ... } )
    

    元素 数组中正在处理的当前元素。

    索引可选 当前正在处理的元素在数组中的索引。

    数组可选 调用了数组映射。

    你的功能

    function add(a: number, b: number = 1) {
      console.log(b) // 0
      return a + b
    }
    console.log([1].map(add)) // [1]
    

    接受

    元素 => 一个

    indexOptional => b

    所以你所做的就是用它的索引添加数组值,你的 b 永远不会被分配给 1,因为你总是得到元素的索引。

    在上述通话中,您的

    a 将为 1(实际数组第一个元素)

    b 将为 0(第一个元素的索引)

    你得到的结果是 1+0 = 1

    数组中的多个元素也是如此

    【讨论】:

    • 感谢您的解释。这是有道理的。
    猜你喜欢
    • 2015-08-18
    • 2020-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-21
    • 1970-01-01
    • 2019-01-25
    相关资源
    最近更新 更多