很抱歉这太长了,但我陷入困境并试图找出为什么我没有获得值。
此函数应返回作为参数给出的所有 Actor 在其中表演的电影数量。
例如:findNumOfMoviesByActors(["Morgan Freeman", "Bob Gunton"]) 应返回 1,因为只有一部电影两者都在其中(请参见下面的数组)。
这是一大堆电影,但这是一个片段:
const movies = [
{"title": "Beetlejuice",
"actors": "Alec Baldwin, Geena Davis, Annie McEnroe, Maurice Page"},
{"title": "The Cotton Club",
"actors": "Richard Gere, Gregory Hines, Diane Lane, Lonette McKee"},
{"title": "The Shawshank Redemption",
"actors": "Tim Robbins, Morgan Freeman, Bob Gunton, William Sadler"},
{"title": "Crocodile Dundee",
"actors": "Paul Hogan, Linda Kozlowski, John Meillon, David Gulpilil"}]
这是我到目前为止的代码:
const findNumOfMoviesByActors = actors => {
for (i = 0; i < movies.length; i++) {
movies[i].actors = movies[i].actors.split(' ')
}
for (i = 0; i < movies.length; i++) {
let count = 0
if (actors === movies[i].actors) {
count++
}
return count
}
}
const actorCheck = ["Paul Hogan", "Linda Kozlowski"]
let test = findNumOfMoviesByActors(actorCheck)
console.log(test)
最佳答案
您需要用可能的空格来分割字符串,因为您会为电影的第二个 Actor 获得一个前导空格,然后您需要迭代所需的 Actor 或给定的 Actor 并计算电影的出现次数。
如果电影包含所有想要的 Actor ,则增加电影计数。
const
findNumOfMoviesByActors = actors => {
let movieCount = 0;
for (let i = 0; i < movies.length; i++) {
let count = 0;
for (const actor of movies[i].actors.split(/,\s*/)) {
if (actors.includes(actor)) count++;
if (count === actors.length) {
movieCount++;
break;
}
}
}
return movieCount;
},
movies = [{ title: "Beetlejuice", actors: "Alec Baldwin, Geena Davis, Annie McEnroe, Maurice Page" }, { title: "The Cotton Club", actors: "Richard Gere, Gregory Hines, Diane Lane, Lonette McKee" }, { title: "The Shawshank Redemption", actors: "Tim Robbins, Morgan Freeman, Bob Gunton, William Sadler" }, { title: "Crocodile Dundee", actors: "Paul Hogan, Linda Kozlowski, John Meillon, David Gulpilil" }],
actorCheck = ["Paul Hogan", "Linda Kozlowski"];
let test = findNumOfMoviesByActors(actorCheck);
console.log(test)
关于javascript - 将对象数组与另一个数组循环函数进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62496474/