在定义数组后填充数组
Populating arrays after their definition
我有一个包含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})
})
相关文章:
- 将数据推送到数组填充 jqGrid
- 使用 JSON 数组填充输入字段
- 用Javascript中的JSON数组填充HTML
- 动态生成的表格 - 使用数组填充TD值
- 使用数组填充if语句值
- AngularJS:用两个JSON数组填充复选框列表,最初检查了一个数组中的一些项
- 为什么不是't ng表将数据从数组填充到表中
- 在javascript中用数组填充对象
- 高图表 - 从数组填充数据
- 如何从下拉列表中由可观察数组填充的选定项中检索完整对象
- 使用 JavaScript 数组填充下拉选择框
- Javascript array.length 为 0,但数组填充了 40 个项目
- 使用 JSON 数组填充图表
- 数组填充外部函数 - 不可访问的成员
- 用 javascript 数组填充 struts2 select 标签
- 用服务器数组填充 jquery 数组
- 如何使用 json 数组填充 Rails 下拉菜单
- 在用数组填充初始化的数组上使用数组映射的意外行为
- JavaScript 风格的数组填充在 Java 中
- 如何使用 javascript 数组填充 html 标题