我仍然在努力学习,我试图让一群演员加入电影类,我让它发挥作用,但我仍然有问题,因为如果你增加另一个演员,最后一个消失了,我尝试了一个循环,但我什么也做不了。
class Movie {
constructor(title,year,duration){
this.title = title;
this.year = year;
this.duration = duration;
}
addCast(actors){
this.actors = actors
}
}
class Actor {
constructor(name,age)
{
this.name = name;
this.age = age;
}
}
const terminator = new Movie('Terminator I', 1985, 60);
const arnold = new Actor('Arnold Schwarzenegger', 50);
const otherCast = [
new Actor('Paul Winfield', 50),
new Actor('Michael Biehn', 50),
new Actor('Linda Hamilton', 50)
];
//From here it can not be modified
let movieOne = new Movie("Kong","2018","2h30m");
let movieTwo = new Movie("Joker","2019","2h03m");
let movieThree = new Movie("John Wick 3", "2019", "1h49m");
terminator.addCast(arnold);
terminator.addCast(otherCast);
//To here it can not be modified
console.log({movieOne,movieTwo,movieThree,terminator});
看见?阿诺德也应该在演员中,但事实并非如此!谢谢你提前帮忙。
另一件事,这是为了一个节选,我不能修改我评论的行。
发布于 2021-02-06 14:37:58
你有
addCast(actors){
this.actors = actors
}这并不会将传递的参与者数组添加到实例上的actors --它用传递的参数替换实例的actors。调用addCast将导致丢失以前在actors上存在的任何内容。
为了帮助减少bug,它可以帮助适当地命名方法--对于这样的逻辑,我称之为setCast,而不是addCast。
如果要将参数添加到现有强制转换的末尾,并且不确定参数是要添加的单个参与者还是要添加的参与者数组,请使用以下命令:
addCast(actorOrActors) {
if (Array.isArray(actorOrActors)) {
this.actors.push(...actorOrActors);
} else {
this.actors.push(actorOrActors);
}
}
class Movie {
constructor(title, year, duration) {
this.title = title;
this.year = year;
this.duration = duration;
this.actors = [];
}
addCast(actorOrActors) {
if (Array.isArray(actorOrActors)) {
this.actors.push(...actorOrActors);
} else {
this.actors.push(actorOrActors);
}
}
}
class Actor {
constructor(name, age) {
this.name = name;
this.age = age;
}
}
const terminator = new Movie('Terminator I', 1985, 60);
const arnold = new Actor('Arnold Schwarzenegger', 50);
const otherCast = [
new Actor('Paul Winfield', 50),
new Actor('Michael Biehn', 50),
new Actor('Linda Hamilton', 50)
];
//From here it can not be modified
let movieOne = new Movie("Kong", "2018", "2h30m");
let movieTwo = new Movie("Joker", "2019", "2h03m");
let movieThree = new Movie("John Wick 3", "2019", "1h49m");
terminator.addCast(arnold);
terminator.addCast(otherCast);
//To here it can not be modified
console.log({
movieOne,
movieTwo,
movieThree,
terminator
});
发布于 2021-02-06 14:38:05
这是因为在addCast()方法中,每次调用它时,都要替换以前的值,而不是追加它
发布于 2021-02-06 14:40:46
你用第二个addActors电话覆盖了阿诺德。一次只向一组演员添加一个演员。
class Movie {
constructor(title,year,duration){
this.title = title;
this.year = year;
this.duration = duration;
this.actors = [];
}
addCast(actor){
this.actors.push(actor);
}
terminator.addCast(arnold);
terminator.addCast(otherCast[0]);
terminator.addCast(otherCast[1]);
terminator.addCast(otherCast[2]);https://stackoverflow.com/questions/66078000
复制相似问题