在定义数组后填充数组

Populating arrays after their definition

本文关键字:数组 填充 定义      更新时间:2023-09-26

我有一个包含li ul,其中包含食谱页面的不同食谱成分的名称。我正在尝试获取这些成分并将它们存储在对象中的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 中使用数组,所以对它们几乎没有经验。

打开控制台并运行它

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>

这应该输出:

{
    "title": "Pork and beans",
    "ingredients": [
        { name : "Pork", optional : false },
        { name : "Beans", optional : false },
        { name : "Salt*", optional : true}
    ]
}
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;
 var rObj = {
        title: $('h3.title').val(),
        ingredients : []
    };

您可以添加成分:

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