gpt4 book ai didi

javascript - "Don' 中的代码不要害怕函数式编程”

转载 作者:行者123 更新时间:2023-11-30 09:55:06 27 4
gpt4 key购买 nike

我一直在阅读一篇标题为 Don’t Be Scared Of Functional Programming 的文章并且有一段代码我无法理解(粘贴在下面)。该代码的目的是从名为 data 的对象数组中获取一个项目。我不明白的是函数中的函数是如何工作的。当您调用 getItem() 时,item 参数来自哪里?

var data = [
{
name: "Jamestown",
population: 2047,
temperatures: [-34, 67, 101, 87]
},
{
name: "Awesome Town",
population: 3568,
temperatures: [-3, 4, 9, 12]
}
{
name: "Funky Town",
population: 1000000,
temperatures: [75, 75, 75, 75, 75]
}
];


function getItem(propertyName) {
// Return a function that retrieves that item, but don't execute the function.
// We'll leave that up to the method that is taking action on items in our
// array.
return function(item) {
return item[propertyName];
}
}

我知道 JS 允许函数作为参数传递,因为它们在 JS 中被视为“一等对象”,但我不明白 item 参数从何而来。

最佳答案

这是在定义一个函数,该函数将接受一个名为 item 的参数,该参数可用于从给定的项目返回 propertyName 元素。它是随后传递回 getItem 的调用者的函数。它将按如下方式使用:

var getName = getItem('name');
var result = getName(x);

其中 x 是一个包含名为“name”的属性的变量

关于javascript - "Don' 中的代码不要害怕函数式编程”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34455331/

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