簡體   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