我不知道为什么我在此功能中出现错误

时间:2019-06-27 17:33:38

标签: javascript

我不明白为什么它可以读取属性“名称”,但是却不能读取属性“价格”。.我在函数addDishToCourse中定义了这两个属性,所以我看不到是什么原因引起的

addDishToCourse(courseName, dishName, dishPrice) {
    const dish = {

      name: dishName,
      price: dishPrice

    };
    this._courses[courseName].push(dish)
  },


  generateRandomMeal: function() {
    const appetizer = this.getRandomDishFromCourse('appetizers');
    const mains = this.getRandomDishFromCourse('mains');
    const desserts = this.getRandomDishFromCourse('desserts');
    const totalPrice = appetizer.price + mains.price + desserts.price;
    return `Your meal is ${appetizer.name}, ${mains.name}, ${desserts.name}. The price is ${totalPrice}.`
  }

getRandomDishFromCourse: function(courseName){ let dishes = menu._courses[courseName] return dishes[Math.floor(Math.random() * dishes.length)];

这是错误: const totalPrice =开胃菜。价格+主菜。价格+甜点。价格;                                                              ^

TypeError:无法读取未定义的属性“ price”     在Object.generateRandomMeal

1 个答案:

答案 0 :(得分:0)

这些主食,甜点或开胃菜的尝试之一不确定。 尝试将它们默认设置为空对象。

addDishToCourse (courseName, dishName, dishPrice) {
   const dish = {

     name : dishName,
     price : dishPrice

   };
   this._courses[courseName].push(dish)
 },


generateRandomMeal: function(){
  const appetizer = this.getRandomDishFromCourse('appetizers') || {};
  const mains = this.getRandomDishFromCourse('mains') || {};
  const desserts = this.getRandomDishFromCourse('desserts') || {};
  const totalPrice = appetizer.price + mains.price + desserts.price;
  return `Your meal is ${appetizer.name}, ${mains.name}, ${desserts.name}. The price is ${totalPrice}.`
}```