繁体   English   中英

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

[英]How to add an array to an object in JavaScript?

我正在尝试将名为成分的数组添加到名为 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());

原型应该在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());

希望这可以帮助,

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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