提问人:McNaughty 提问时间:10/8/2023 最后编辑:NimanthaMcNaughty 更新时间:10/8/2023 访问量:28
如何在 JavaScript 中使用数组查找方法:预期未定义等于“2015”?
How can I use Array find method in JavaScript: expected undefined to equal '2015'?
问:
我正在尝试编写一个使用 find() 返回超级碗获胜年份(“W”)的函数。这是数组对象
const record = [
{ year: "2018", result: "N/A"},
{ year: "2017", result: "N/A"},
{ year: "2016", result: "N/A"},
{ year: "2015", result: "W"},
{ year: "2014", result: "N/A"},
{ year: "2013", result: "L"},
{ year: "2012", result: "N/A"},
{ year: "2011", result: "N/A"},
{ year: "2010", result: "N/A"},
{ year: "2009", result: "N/A"},
{ year: "2008", result: "N/A"},
{ year: "2007", result: "N/A"},
{ year: "2006", result: "N/A"},
{ year: "2005", result: "N/A"},
{ year: "2004", result: "N/A"},
{ year: "2003", result: "N/A"},
{ year: "2002", result: "N/A"},
{ year: "2001", result: "N/A"},
{ year: "2000", result: "N/A"},
{ year: "1999", result: "N/A"},
{ year: "1998", result: "W"},
{ year: "1997", result: "W"},
{ year: "1996", result: "N/A"},
{ year: "1995", result: "N/A"},
{ year: "1994", result: "N/A"},
{ year: "1993", result: "N/A"},
{ year: "1992", result: "N/A"},
{ year: "1991", result: "N/A"},
{ year: "1990", result: "N/A"},
{ year: "1989", result: "L"},
{ year: "1988", result: "N/A"},
{ year: "1987", result: "L"},
{ year: "1986", result: "L"},
{ year: "1985", result: "N/A"},
{ year: "1984", result: "N/A"},
{ year: "1983", result: "N/A"},
{ year: "1982", result: "N/A"},
{ year: "1981", result: "N/A"},
{ year: "1980", result: "N/A"},
{ year: "1979", result: "N/A"},
{ year: "1978", result: "N/A"},
{ year: "1977", result: "N/A"},
{ year: "1976", result: "L"},
{ year: "1975", result: "N/A"},
{ year: "1974", result: "N/A"},
{ year: "1973", result: "N/A"},
{ year: "1972", result: "N/A"},
{ year: "1971", result: "N/A"},
{ year: "1970", result: "N/A"},
{ year: "1969", result: "N/A"},
{ year: "1968", result: "N/A"},
{ year: "1967", result: "N/A"},
{ year: "1966", result: "N/A"},
{ year: "1965", result: "N/A"},
{ year: "1964", result: "N/A"},
{ year: "1963", result: "N/A"},
{ year: "1962", result: "N/A"},
{ year: "1961", result: "N/A"},
{ year: "1960", result: "N/A"}
]
function superbowlWin (element){
if(element.result === "W"){
const winYear = element.year
return winYear;
}
}
console.log(record.find(superbowlWin).year);`
我的测试失败,出现以下错误:
超级碗赢(记录) 1) 丹佛野马队赢得 Superbowl ✓ 如果记录没有获胜对象,则返回 undefined
1 次通过 (377ms) 1 次失败
- 超级碗赢(记录)。丹佛野马队赢得 超级碗。AssertionError:在上下文中,预期未定义等于“2015”。(test/indexTest.js:66:33) 在进程立即 (内部/计时器.js:461:21)
我原以为回报胜利年等于2015年。
答:
0赞
Hezy Ziv
10/8/2023
#1
您的问题在于您的查找请求没有价值。返回值未定义,则您正在尝试获取未定义对象的年份。
尝试:
function superbowlWin(records){
const winRecord = records.find(element => element.result === "W");
return winRecord ? winRecord.year : undefined;
}
console.log(superbowlWin(record));
该行检查是否有值,如果是,则返回年份,如果没有,则返回未定义。return winRecord ? winRecord.year : undefined;
winRecord
评论