如何在JavaScript中向对象添加数组?

时间:2019-04-15 02:22:01

标签: javascript arrays constructor

我试图将名为配料的数组添加到名为addIngredients的对象中,以便在调用方法displayRecipe()时,它将在控制台窗口中显示myFavoriteRecipe()对象和该数组。我收到一条错误消息,提示未定义displayRecipe()。为什么以及如何解决这个问题?

var ingredients = [];

function myFavoriteRecipe() {
    "use strict";
     this.title = "guacamole";
     this.serves = 8;
    
}

function addIngredients(items) {
    "use strict";
    //CREATING INSTANCE
    var foodItems = new myFavoriteRecipe ();
    //Pushing ingredients to food items
    ingredients.push(foodItems);
    return items;
}

addIngredients("3 Avocados");
addIngredients("1 Lime");
addIngredients("1 TSP salt");
addIngredients("1/2 Cup Onion");
addIngredients("3 Tablespoons of Cilantro");
addIngredients("2 Diced Tomatoes");
addIngredients("1 pinch Ground Pepper");

addIngredients.prototype.displayRecipe = function() {
    "use strict";
    for (var items in addIngredients) {
        return addIngredients[items];
    }
}
  
window.console.log(displayRecipe());

1 个答案:

答案 0 :(得分:1)

应将原型设置在myFavoriteRecipe上,而不是addIngredients上。

请看看这个:

function myFavoriteRecipe(info) {
  this.title = info.title || 'Not Set';
  this.serves = info.serves || 0;
  this.ingredients = [];
  this.addIngredients = function(items) {
    this.ingredients.push(items);
  };
}
myFavoriteRecipe.prototype.displayRecipe = function() {
  return this.ingredients;
}

let recipe = new myFavoriteRecipe({
  title: 'guacamole',
  serves: 8
});
recipe.addIngredients("3 Avocados");
recipe.addIngredients("1 Lime");
recipe.addIngredients("1 TSP salt");
recipe.addIngredients("1/2 Cup Onion");
recipe.addIngredients("3 Tablespoons of Cilantro");
recipe.addIngredients("2 Diced Tomatoes");
recipe.addIngredients("1 pinch Ground Pepper");

console.log(recipe.displayRecipe());

希望这会有所帮助,