简体   繁体   中英

How to add an array to an object in JavaScript?

I am trying to add the array named ingredients to the object named addIngredients so that when the method displayRecipe() is called it will display both the myFavoriteRecipe() object and also the array by showing it in the console window. I am getting an error message saying displayRecipe() is not defined. Why and how can I fix this?

 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());

The prototype should be set on myFavoriteRecipe , not on addIngredients .

Please take a look at this:

 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());

Hope this helps,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM