Codecademy JavaScript图书馆项目:console.log输出undefined问题求助
修复JavaScript图书馆项目中的printString()和info()方法问题
问题分析
你遇到的核心问题:
- printString内容提前输出:
printString()方法内部直接调用console.log(),在info()里调用该方法时会立即执行输出,而非作为字符串拼接的一部分。 - info()输出末尾带undefined:
printString()无返回值(默认返回undefined),字符串拼接时会将undefined追加到末尾。 - 额外问题:Movie类构造函数未将传入的
cast参数赋值给实例属性,导致输出中staring后为空;部分实例化参数顺序颠倒,导致信息错位。
修复后的完整代码
// 父类 class Media { constructor(title) { this._title = title; this._isCheckedOut = false; this._ratings = []; } get title() { return this._title; } get isCheckedOut() { return this._isCheckedOut; } get ratings() { return this._ratings; } toggleCheckOutStatus() { this._isCheckedOut = !this.isCheckedOut; } getAverageRating() { if (this.ratings.length === 0) { return 0; } const sum = this.ratings.reduce((acc, val) => acc + val, 0); return Math.round(sum / this.ratings.length); } addRating(rating) { if (rating >= 1 && rating <= 5) { this.ratings.push(rating); } else { console.error( `Sorry, the Rating for ${this.title} must be between 1 and 5.` ); } } set isCheckedOut(checkedIn) { this._isCheckedOut = checkedIn; } // 修改:返回字符串而非直接console.log printString() { if (this.isCheckedOut) { return `${this.title} is checked out. Talk to an associate to get on a wait list for this ${this.constructor.name}.`; } else { return `${this.title} is available. Speak to an associate for assistance finding this ${this.constructor.name}.`; } } info() { let mediaInfo = ''; if (this instanceof Book) { mediaInfo = `${this.title}, written by ${this.author}, is ${this.pages} pages. ${this.title} is rated ${this.getAverageRating()} stars by readers.`; } else if (this instanceof Movie) { mediaInfo = `${this.title}, directed by ${this.director}, starring ${this.cast}, has a ${this.runTime} minute run time. ${this.title} is rated ${this.getAverageRating()} stars by watchers.`; } else if (this instanceof CD) { mediaInfo = `${this.title}, by ${this.artist}, has ${this.songs} songs. The songs on this album are ${this.songTitles}.\n${this.title} is rated ${this.getAverageRating()} stars by listeners.`; } else { mediaInfo = `This title is not available at this location. Please ask an associate for assistance.`; } // 分两次输出,避免拼接undefined console.log(mediaInfo); console.log(this.printString()); } } // 子类 class Book extends Media { constructor(title, author, pages) { super(title); this._author = author; this._pages = pages; } get author() { return this._author; } get pages() { return this._pages; } } class Movie extends Media { constructor(title, director, runTime, cast) { super(title); this._director = director; this._runTime = runTime; // 修改:赋值传入的cast参数 this._cast = cast; } get director() { return this._director; } get runTime() { return this._runTime; } get cast() { return this._cast; } } class CD extends Media { constructor(title, artist, songs, songTitles) { super(title); this._artist = artist; this._songs = songs; this._songTitles = songTitles; } get artist() { return this._artist; } get songs() { return this._songs; } get songTitles() { return this._songTitles; } } // 实例化及测试代码 const historyOfEverything = new Book( "A Short History of Nearly Everything", "Bill Bryson", 544 ); // 修正参数顺序 const theGreatGatsby = new Book("The Great Gatsby", "F. Scott Fitzgerald", 180); const jekyllAndHyde = new Book( "Dr. Jekyll and Mr. Hyde", "Robert Louis Stevenson, Vladimir Nabokov (Introduction), Dan Chaon (Afterword)", 139 ); const sherlockHolmes = new Book( "The Complete Sherlock Holmes", "Arthur Conan Doyle", 1796 ); const speed = new Movie( "Speed", "Jan de Bont", 116, "Keanu Reeves, Dennis Hopper, Sandra Bullock, Joe Morton, Jeff Daniels" ); const snowWhite = new Movie( "Snow White and the Seven Dwarfs", "David Hand", 79, "Adriana Caselotti, Harry Stockwell, Lucille LaVerne, Moroni Olsen, Billy Gilbert, Billy Gilbert, Pinto Colvig, Otis Harlan, Scotty Mattraw, Roy Atwell" ); const theEdge = new Movie( "The Edge", "Lee Tamahori", 212, "Anthony Hopkins, Alec Baldwin, Elle Macpherson, Harold Perrineau" ); const marley = new Movie( "Marley & Me", "David Frankel", 115, "Owen Wilson, Jennifer Aniston" ); const endlessProcessionOfSouls = new CD( "Grave", "Endless Procession Of Souls", 10, "Dystopia, Amongst Marble and the Dead, Disembodied Steps, Flesh Epistle, Passion of the Weak, Winds of Chains, Encountering the Divine, Perimortem, Plague of Nations, Plague of Nations, Epos" ); // 修正参数顺序 const comeGetIt = new CD( "Come Get It!", "Rick James", 9, "Stone City Band, Hi!, You And I, Sexy Lady, Dream Maker, Be My Lady, Mary Jane, Hollywood, Stone City Band, Bye!, You And I - Extended M+M Mix" ); const aTribeCalledRed = new CD( "The Halluci Nation", "A Tribe Called Red", 9, "Electric Pow Wow Drum, Look at This - Remix, Northern Cree - Red Skin Girl - A Tribe Called Red Remix, Woodcarver, Good to Go, Munchi - Shottas - A Tribe Called Red Socacore Remix, Native Puppy Love, Moombahwow, Intertribal N.1" ); // 修正参数顺序 const bachImprovisations = new CD( "Bach Improvisations", "Ira Stein", 9, "Cantata No. 122, Cantata No. 11, Cantata No. 31, Christmas Oratorio, Choral for 4 voices (Liebster jesu), Choral for 4 voices (O Mensch), Chorale for 4 voices (Wir glauben all en einen Gott), Jesu, Chorale for 4 voices (Komm)" ); historyOfEverything.toggleCheckOutStatus(); theGreatGatsby.toggleCheckOutStatus(); historyOfEverything.addRating(5); historyOfEverything.addRating(3); historyOfEverything.addRating(5); theGreatGatsby.addRating(4); theGreatGatsby.addRating(3); theGreatGatsby.addRating(4); theGreatGatsby.addRating(2); theGreatGatsby.addRating(4); jekyllAndHyde.addRating(5); jekyllAndHyde.addRating(4); jekyllAndHyde.addRating(4); jekyllAndHyde.addRating(5); jekyllAndHyde.addRating(1); jekyllAndHyde.addRating(5); jekyllAndHyde.addRating(3); jekyllAndHyde.addRating(1); jekyllAndHyde.addRating(2); jekyllAndHyde.addRating(4); sherlockHolmes.addRating(1); sherlockHolmes.addRating(5); sherlockHolmes.addRating(5); sherlockHolmes.addRating(5); speed.toggleCheckOutStatus(); snowWhite.toggleCheckOutStatus(); marley.toggleCheckOutStatus(); speed.addRating(1); speed.addRating(1); speed.addRating(5); snowWhite.addRating(5); snowWhite.addRating(3); snowWhite.addRating(5); snowWhite.addRating(4); theEdge.addRating(5); theEdge.addRating(1); theEdge.addRating(2); theEdge.addRating(4); theEdge.addRating(4); marley.addRating(5); marley.addRating(5); marley.addRating(5); marley.addRating(5); marley.addRating(5); marley.addRating(4); marley.addRating(4); marley.addRating(1); endlessProcessionOfSouls.addRating(5); endlessProcessionOfSouls.addRating(4); endlessProcessionOfSouls.addRating(2); endlessProcessionOfSouls.addRating(4); endlessProcessionOfSouls.addRating(4); comeGetIt.addRating(5); comeGetIt.addRating(4); comeGetIt.addRating(3); comeGetIt.addRating(5); comeGetIt.addRating(4); aTribeCalledRed.addRating(2); aTribeCalledRed.addRating(4); aTribeCalledRed.addRating(4); aTribeCalledRed.addRating(3); bachImprovisations.addRating(5); bachImprovisations.addRating(4); bachImprovisations.addRating(3); bachImprovisations.addRating(3); bachImprovisations.addRating(2); jekyllAndHyde.info(); endlessProcessionOfSouls.info(); marley.info();
关键修改说明
- 重构printString():将直接输出改为返回字符串,避免提前输出,同时修正拼写错误(
avalible→available、Speek→Speak)。 - 调整info()逻辑:分两次输出媒体详情和借阅状态,彻底解决
undefined拼接问题,修正staring→starring拼写错误。 - 修复Movie类构造函数:将传入的
cast参数赋值给实例属性,解决演员列表为空的问题。 - 修正实例参数顺序:调整部分Book、CD实例的参数顺序,使其符合构造函数定义(title在前,创作者在后)。
内容的提问来源于stack exchange,提问作者Bri Dobbs
相关产品推荐
相关产品推荐

