【问题标题】:Can you use an array as an object’s property value?你可以使用数组作为对象的属性值吗?
【发布时间】: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


【解决方案1】:

在您的 javascript 的第 3 行中,您将成分定义为一个空数组。您可以通过编写来解决此问题

this.ingredients = ingredients

相反。如果你愿意,你也可以使用一个叫做解构的漂亮工具,你可以把它写成

this.ingredients = [...ingredients]

【讨论】:

    【解决方案2】:

    请先尝试学习调试。您的问题是您没有对成分参数做任何事情。

    你的功能应该是:

    function Recipe(name, ingredients) {
        this.name = name;
        this.ingredients = 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;
    document.getElemendById("name1").innerHTML = recipe1Name;
    
    var recipe1Ingredients = recipe1.ingredients;
    insertToIngredients = "";
    for (var i = 0; i<recipe1Ingerdients.length; i++) {
        insertToIngredients = insertToIngredients + "<br>"+ recipe1Ingredients[i];
    }
    document.getElementById("ingredients1").innerHTML = insertToIngredients;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-22
      • 2015-12-23
      • 2019-06-02
      • 2019-05-14
      • 2011-03-05
      • 2023-03-25
      • 2022-07-27
      • 1970-01-01
      相关资源
      最近更新 更多