gpt4 book ai didi

javascript - 映射函数返回带有索引而不是字符串值的数组

转载 作者:行者123 更新时间:2023-11-30 11:42:56 25 4
gpt4 key购买 nike

在我的 map 函数中观察到奇怪的行为:

let tpl = ({x}, y = `This is ${x}`) => y;

console.log( tpl({x:5}) ); //correctly returns 'This is 5'

console.log( [{x:1}, {x:9}].map(tpl) ); //expecting array of strings, instead get [0, 1]

可以通过省略默认变量 y 并直接从 tpl 返回模板字符串来“修复”这个问题。但是,我更愿意以这种方式进行初始化,但不明白为什么它仍然无法正常工作。

对我来说似乎是一个奇怪的异常现象,有人对我遗漏的东西有洞察力吗?

最佳答案

您的tpl 函数由JavaScript 的map Array 方法提供(value, index, array)。您已经为 y 指定了默认值 This is ${x}。但是当您将 tpl 作为回调传递给 map 时,y 不是未定义的,因此不使用默认值。 map 将索引传递给您的 y 参数。

let tpl = ({x}, y = `This is ${x}`) => y
const arr = [ {x:1}, {x:9} ];
arr.map(tpl) // [0, 1]
arr.map((value, index, array) => tpl(value)) // [ 'This is 1', 'This is 9' ]

Array.prototype.map()

Default parameters

关于javascript - 映射函数返回带有索引而不是字符串值的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41971759/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com