在定义后填充数组

时间:2015-03-16 18:12:50

标签: javascript jquery arrays

我有ul包含li,其中包含食谱页面的不同食谱成分的名称。我正在尝试获取这些成分并将它们存储到对象中的JavaScript数组中。我已经知道了食谱的标题,所以我把它放到了对象属性title中,但我不知道每个食谱会有多少成分。这就是我所拥有的:

var recipeobj = {
        title: $('h3.title').val(),
        ingredients: [
                ingredient,
                optional
        ]
    }
    $.each($('ul.ingredients > li > h4'), function (index, ingredient) {
        recipeobj.ingredients[index].ingredient = $(ingredient).html();
        recipeobj.ingredients[index].optional = false;
    })

如果我尝试console.log(recipeobj.ingredients),我只会收到错误Uncaught ReferenceError: ingredient is not defined

毫无疑问,这很简单,我很少需要在JavaScript中使用数组,所以对它们几乎没有经验。

3 个答案:

答案 0 :(得分:0)

var rObj = {
        title: $('h3.title').val(),
        ingredients: [
                'source cream',
                'cheese',
                'chopped meat'
        ],
        optional: true
    };

访问

var rItem = rObj.ingredients[1];

或者你想要

var rObj = {
        title: $('h3.title').val(),
        ingredients: {
                ingredient_list: ['one','two','three'],
                optional: true
        }
    };

访问

var rItem = rObj.ingredients.ingredient_list[1];

您尝试使用的结构看起来像结构应该像

var rObj = {
            title: $('h3.title').val(),
            things: [{
                ingredient: 'source cream',
                optional: true
            },
            {
                ingredient: 'cheese',
                optional: false
            }]
        };

访问

var ingred = rObj.things[1].ingredient;

答案 1 :(得分:0)

打开控制台并运行



var recipeobj = {
  title: $('h3.title').html(),
  // ingredients is empty for now
  ingredients: []
};

$.each($('ul.ingredients > li > h4'), function(index, ingredient) {
  // Get the name
  var name = $(ingredient).html(),
      // Find out if it is 'optional'(using a class here)
      optional = $(ingredient).hasClass('optional');
  // Push a new ingredient into the array
  recipeobj.ingredients.push({ name: name, optional: optional });
});

console.log(recipeobj);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3 class="title">Pork and beans</h3>

<ul class="ingredients">
  <li>
    <h4>Pork</h4>
  </li>
  <li>
    <h4>Beans</h4>
  </li>
  <li>
    <h4 class="optional">Salt*</h4>
  </li>
</ul>
&#13;
&#13;
&#13;

这应输出:

{
    "title": "Pork and beans",
    "ingredients": [
        { name : "Pork", optional : false },
        { name : "Beans", optional : false },
        { name : "Salt*", optional : true}
    ]
}

答案 2 :(得分:0)

 var rObj = {
        title: $('h3.title').val(),
        ingredients : []
    };

你可以添加成分:

      $.each($('ul.ingredients > li > h4'), function (index, ingredient) {
     rObj.ingredients.push({ingredient: $(ingredient).html(), optional       :false})
 })