对于这个函数,我构建了几个函数和一个高阶函数。我希望将这三个较小的函数作为参数传递给高阶函数。当我尝试调用高阶函数并作为参数传递时,我得到一个错误,即回调不是一个函数。有什么想法吗?
{
"Year": 2002,
"Datetime": "02 Jun 2002 - 18:30",
"Stage": "Group F",
"Stadium": "Saitama Stadium 2002",
"City": "Saitama",
"Home Team Name": "England",
"Home Team Goals": 1,
"Away Team Goals": 1,
"Away Team Name": "Sweden",
"Win conditions": "",
"Attendance": 52721,
"Half-time Home Goals": 1,
"Half-time Away Goals": 0,
"Referee": "SIMON Carlos (BRA)",
"Assistant 1": "OLIVEIRA Jorge (BRA)",
"Assistant 2": "DUPANOV Yuri (BLR)",
"RoundID": 43950100,
"MatchID": 43950005,
"Home Team Initials": "ENG",
"Away Team Initials": "SWE"
},
{
"Year": 2002,
"Datetime": "02 Jun 2002 - 20:30",
"Stage": "Group B",
"Stadium": "Gwangju World Cup Stadium",
"City": "Gwangju",
"Home Team Name": "Spain",
"Home Team Goals": 3,
"Away Team Goals": 1,
"Away Team Name": "Slovenia",
"Win conditions": "",
"Attendance": 28598,
"Half-time Home Goals": 1,
"Half-time Away Goals": 0,
"Referee": "GUEZZAZ Mohammed (MAR)",
"Assistant 1": "TOMUSANGE Ali (UGA)",
"Assistant 2": "BEREUTER Egon (AUT)",
"RoundID": 43950100,
"MatchID": 43950008,
"Home Team Initials": "ESP",
"Away Team Initials": "SVN"
},
]
function getFinals(arr)
{
return arr.filter(team => team.Stage === "Final");
}
//console.log(getFinals(fifaData));
function getYears(arr, callback)
{
const years = callback(arr).map(team => team.Year);
return years;
}
function getWinners(arr, func)
{
const winners = [];
const winIt = func(arr);
console.log(winIt);
for (let i = 0; i < winIt.length; i++)
{
if(winIt[i]['Home Team Goals'] > winIt[i]['Away Team Goals'])
{
winners.push(winIt[i]['Home Team Name']);
}
else
{
winners.push(winIt[i]['Away Team Name']);
}
}
return winners
}
function getWinnersByYear(arr, cbThree, cbFour,cbFive)
{
const years = cbThree(arr, cbFive);
const winners = cbFour(arr, cbThree);
const full = [];
for(let j = 0; j < years.length; j++)
{
full.push(`In ${years[j]}, ${winners[j]} won the world cup!`);
}
return full;
}
console.log(getWinnersByYear(fifaData, getYears, getWinners, getFinals));发布于 2021-05-07 21:22:33
在getWinners中,调用getYears时只有一个参数
function getWinners(arr, func) // <- getYears was passed as `func`
{
const winners = [];
const winIt = func(arr); // <- here在JS中,在函数调用中省略参数相当于为该参数提供undefined。
所以在这个调用中,参数callback被赋值为undefined,它实际上不是一个函数(因此不能被调用)。
我建议给你的参数起有意义的名字。它提高了可读性,并有助于跟踪这类错误。
一般的流程也可以简化,减少对回调的大量使用-例如,在getYears中:考虑如何直接传递callback(arr)的结果,而不是arr和callback的结果会更简单、更等价。
https://stackoverflow.com/questions/67429128
复制相似问题