You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript代码中.push调用报undefined错误求助

Fixing Your JavaScript Menu Object Errors

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 be generateRandomMeal), you call getRandomDishFromCourse without this.—this will throw a reference error because the method is part of the menu object, so you need to access it via this.
  • 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_desserts instead of _courses.desserts can break your code silently.
  • Don't forget this for object methods: When calling a method inside another method of the same object, you need to prefix it with this. to access the correct context.

内容的提问来源于stack exchange,提问作者Ryan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 21:02:34