【发布时间】:2019-09-13 17:11:43
【问题描述】:
给定以下数据库
DB = [
{
genre:'thriller',
movies:[
{
title:'the usual suspects', release_date:1999
}
]},
{
genre:'commedy',
movies:[
{
title:'pinapple express', release_date:2008
}
]}
]
我想检查其中是否存在流派和电影,如果没有则添加。
到目前为止,我有这个代码。唯一缺少的是,如果电影不存在(注释掉并加粗),则将(新)电影推送到类型索引处。
var moviesDB = function (array, genre, movie) {
var x = []
for (var i = 0; i < DB.length; i++) {
x.push(DB[i].genre);
}
if(x.includes(genre) == false) {
DB.push({genre: genre, movies: []});
} else {
console.log("genre already here")
}
var y = []
for (var i = 0; i < DB.length; i++) {
DB[i].movies.forEach (function (object){
y.push(object.title)
})
}
if(y.includes(movie) == false) {
//**push movie into the existing object.**
} else {
return `the movie the ${movie} is already in the database!`
}
return DB;
}
Sp moviesDB = function (DB, "drama", "A drama movie")应该添加一个新的流派对象(戏剧),并在电影数组中添加一个标题为“戏剧电影”的新对象。而moviesDB = function (DB, "commedy", "Scary movie") 应该只在现有的喜剧流派对象中添加一个带有电影标题的新对象。
DB = [
{
genre:'thriller',
movies:[
{
title:'the usual suspects', release_date:1999
}
]},
{
genre:'commedy',
movies:[
{
title:'pinapple express', release_date:2008
}
]}
]
var moviesDB = function (array, genre, movie) {
var x = []
for (var i = 0; i < DB.length; i++) {
x.push(DB[i].genre);
}
if(x.includes(genre) == false) {
DB.push({genre: genre, movies: []});
} else {
console.log("genre already here")
}
var y = []
for (var i = 0; i < DB.length; i++) {
DB[i].movies.forEach (function (object){
y.push(object.title)
})
}
if(y.includes(movie) == false) {
//**push movie into the existing object.**
} else {
return `the movie the ${movie} is already in the database!`
}
return DB;
}
console.log(moviesDB(DB, "drama", "A drama movie"))
【问题讨论】:
-
尽可能保留代码结构,只帮助我突出显示的一行,因为这是我目前拥有的水平和技术。
-
请点击edit然后
[<>]创建一个minimal reproducible example - 很难猜出你如何调用你的moviesDB,看起来你在不应该循环的地方循环 -
参数
array从未在您的函数中使用。 Imo 在该函数中出现的所有DB都应替换为array,或者必须删除array参数。 -
@3limin4t0r 当然,我在调用函数时使用它
-
是的,您将它传递给函数,但从未在函数中实际使用它。尝试将
moviesDB(DB, "drama", "A drama movie")替换为moviesDB(undefined, "drama", "A drama movie"),您会看到产生相同的结果。
标签: javascript arrays loops object conditional-statements