JavaScript代码中.push调用报undefined错误求助
Hey there! Let's break down the issues in your code step by step so you can understand exactly what's going wrong and avoid these pitfalls in the future.
Key Issues Causing the undefined Error
1. Mismatched Course Name Plurality
Your _courses object defines properties using plural names: appetizers, mains, desserts. But when you call addDishToCourse, you're passing singular names: 'appetizer', 'main', 'dessert'.
Since this._courses['appetizer'] doesn't exist (it's appetizers), it returns undefined—and you can't call .push() on undefined. That's the root of your main error.
2. Typo in the Dessert Setter Method
Look at your desserts setter:
set desserts(desserts) { this._courses_desserts = desserts; }
You wrote _courses_desserts (with an underscore) instead of _courses.desserts. This means setting desserts won't actually update the correct property in your _courses object.
3. Missing this & Typo in Meal Generation
- In
generateRandmMeal(note the typo: should begenerateRandomMeal), you callgetRandomDishFromCoursewithoutthis.—this will throw a reference error because the method is part of themenuobject, so you need to access it viathis. - You also use singular course names here (
'appetizer'instead of'appetizers'), which would still cause issues even if the first problem was fixed.
Corrected Code
const menu = { _courses: { appetizers: [], mains: [], desserts: [] }, get appetizers() { return this._courses.appetizers; }, get mains() { return this._courses.mains; }, get desserts() { return this._courses.desserts; }, set appetizers(appetizers) { this._courses.appetizers = appetizers; }, set mains(mains) { this._courses.mains = mains; }, set desserts(desserts) { this._courses.desserts = desserts; // Fixed typo here }, get courses() { return { appetizers: this.appetizers, mains: this.mains, desserts: this.desserts }; }, addDishToCourse(courseName, dishName, dishPrice) { const dish = { name: dishName, price: dishPrice, }; return this._courses[courseName].push(dish); }, getRandomDishFromCourse(courseName) { const dishes = this._courses[courseName]; const randomIndex = Math.floor(Math.random() * dishes.length); return dishes[randomIndex]; }, generateRandomMeal() { // Fixed typo in method name const appetizer = this.getRandomDishFromCourse('appetizers'); // Added this. + plural name const main = this.getRandomDishFromCourse('mains'); const dessert = this.getRandomDishFromCourse('desserts'); const totalPrice = appetizer.price + main.price + dessert.price; return `Your meal is ${appetizer.name}, ${main.name}, ${dessert.name} and your total is $${totalPrice.toFixed(2)}`; } }; menu.addDishToCourse('appetizers', 'Wings', 4.00); // Plural course name menu.addDishToCourse('mains', 'Grilled Steak', 5.00); menu.addDishToCourse('desserts', 'Chocolate Cake', 3.00); // Test it out! console.log(menu.generateRandomMeal());
Takeaways to Avoid Future Errors
- Double-check property name consistency: Make sure the keys you're accessing match exactly what's defined in your objects (singular vs plural is a common gotcha).
- Watch for typos in property/method names: Small mistakes like
_courses_dessertsinstead of_courses.dessertscan break your code silently. - Don't forget
thisfor object methods: When calling a method inside another method of the same object, you need to prefix it withthis.to access the correct context.
内容的提问来源于stack exchange,提问作者Ryan

