我的程序非常简单-它应将影片保存在数组中,然后以JSON格式打印。问题在于“ contains()”方法(我认为)。它可以很好地与名字电影一起使用,但是当名字中包含空格时,它将返回null。这是代码。
function movieDirectors(array) {
let movies = [];
class Movie {
constructor(name, director, date) {
this.name = name;
this.director = director;
this.date = date;
}
}
let contains = function (movieName) {
let movie = null;
movies.forEach(m => m.name === movieName ? movie = m : movie = null);
return movie;
}
for (let i = 0; i < array.length; i++) {
let command = array[i].split(' ');
if (command.includes('addMovie')) {
let name = command.slice(1, command.length).join(' ');
movies.push(new Movie(name, null, null));
} else if (command.includes('directedBy')) {
let name1 = command.slice(0, command.indexOf('directedBy')).join(' ');
if (contains(name1) !== null) {
let movie = contains(name1);
movie.director = command.slice(command.indexOf('directedBy') + 1, command.length).join(' ');
}
} else if (command.includes('onDate')) {
let name2 = command.slice(0, command.indexOf('onDate')).join(' ');
if (contains(name2) !== null) {
let movie = contains(name2);
movie.date = command.slice(command.indexOf('onDate') + 1, command.length).join(' ');
}
}
}
movies.forEach(m => m.director != null && m.name != null && m.date != null ? console.log(JSON.stringify(m)) : null);
}
movieDirectors([
'addMovie Fast and Furious',
'addMovie Godfather',
'Godfather directedBy Francis Ford Coppola',
'Godfather onDate 29.07.2018',
'Fast and Furious onDate 30.07.2018',
'Fast and Furious directedBy Rob Cohen']);
输出必须是这样的:
{"name":"Fast and Furious","date":"30.07.2018","director":"Rob Cohen"}
{"name":"Godfather","director":"Francis Ford Coppola","date":"29.07.2018"}
我的JavaScript语言非常环保,非常感谢您帮助我理解语言的这些精妙之处。
contains
当找到具有给定名称的电影时,该函数将停止并返回。
它将起作用:
let contains = function (movieName) {
return movies.find(m => m.name === movieName);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句