[英]filter function does not return value
我正在使用 Node 和 Express 構建電影 API。 我的過濾器函數沒有返回值,到目前為止我的代碼如下:
class MovieStore{
constructor(){
this.movieData = require('./db/database.json');
}
all(){
return this.movieData;
}
findMovie(tittle){
return this.movieData.filter(movie => movie.Tittle === tittle);
}
}
過濾功能有問題嗎? 即使我從 URL 傳遞了 params 值,它也只返回[]
。
這是我的json:
[
{
"Title":"Guardians of the Galaxy Vol. 2",
"Year":"2017",
"Rated":"PG-13",
"Released":"05 May 2017",
"Runtime":"136 min",
"Genre":"Action, Adventure, Comedy",
"Director":"James Gunn",
"Writer":"James Gunn"
}
]
我的過濾器函數沒有返回值......它只返回 []
您的過濾器代碼工作正常,只需要一個小的錯字修復(在下面的評論中突出顯示):
/* define our test database */ const inMemoryDatabase = [ { "Title":"Guardians of the Galaxy Vol. 2", "Year":"2017", "Rated":"PG-13", "Released":"05 May 2017", "Runtime":"136 min", "Genre":"Action, Adventure, Comedy", "Director":"James Gunn", "Writer":"James Gunn" }, { "Title":"Pacific Rim", "Year":"2013", "Director":"Guillermo del Toro", "Writer":"Travis Beacham" } ] /* define your class */ class MovieStore{ constructor(){ this.movieData = inMemoryDatabase } all(){ return this.movieData; } findMovie(tittle){ return this.movieData.filter(movie => movie.Title === tittle); // <- just fixed your typo here; the json database was using key "Title". } } /* create instance of your MovieStore class */ const concreteMovieStore = new MovieStore() console.log("ALL MOVIES IN STORAGE:\\n", concreteMovieStore.all()) /* test filter function */ const movie = concreteMovieStore.findMovie("Guardians of the Galaxy Vol. 2") console.log("SEARCH RESULT: ", movie)
希望這可以幫助。 干杯!
//in .db/database.json
module.exports = [{
"Title":"Guardians of the Galaxy Vol. 2",
"Year":"2017",
"Rated":"PG-13",
"Released":"05 May 2017",
"Runtime":"136 min",
"Genre":"Action, Adventure, Comedy",
"Director":"James Gunn",
"Writer":"James Gunn"
}];
const movieData = require('./db/database.json');;
class MovieStore{
constructor(){}
all(){
return movieData;
}
findMovie(tittle){
return movieData.filter(movie => movie.Tittle.toLowerCase() === tittle.trim().toLowerCase());
}
}
試試上面的代碼,它會解決你的問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.