【发布时间】:2019-11-05 20:24:17
【问题描述】:
我正在尝试为食谱卡编写 JavaScript。我认为使用对象构造函数是最好的,因为我正在使用相同的标准创建多个配方。我需要为配料使用一个数组,但我似乎无法让它发挥作用。唯一会显示的是配方名称,并且数组返回未定义。
我对 JS 非常陌生,所以请像孩子一样为我分解事物,同时也要善良:)
另外,我很抱歉代码是这样写的。我在移动应用程序上,所以我没有像往常一样让我选择将它写在特定的框中。如果您愿意,这里是 CodePen:https://codepen.io/Nikofem/pen/RwwgGog
这是 HTML 代码:
<div class="recipe-card">
<aside>
<img src="https://divascancook.com/wp-content/uploads/2015/01/no-bake-engery-bites-peanut-butter-chocolate-healthy-granola-snack-recipe-2.jpg" alt="Granola Engergy Bites" />
</aside>
<article>
<h2 id="name1"></h2>
<h4 id="ingredients1"></h4>
<ul>
<li><span class="icon icon-users"></span><span>10 - 15</span></li>
<li><span class="icon icon-clock"></span><span>15 min</span></li>
</ul>
</article>
</div>
这是我目前的 JS 代码:
function Recipe(name, ingredients) {
this.name = name;
this.ingredients = [];
}
var recipe1 = new Recipe('Granola Energy Bites', ['1 cup old-fashioned oats', '1/4 tsp salt', '1/4 tsp cinnamon']);
var recipe1Name = recipe1.name;
name1.innerHTML = recipe1Name;
var recipe1Ingredients = recipe1.ingredients[0];
ingredients1.innerHTML = recipe1Ingredients;
【问题讨论】:
-
this.ingredients = []- 除了空数组之外,您永远不会在这里分配任何东西
标签: javascript arrays object constructor