首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >你能有一个双重嵌套的对象文字吗?

你能有一个双重嵌套的对象文字吗?
EN

Stack Overflow用户
提问于 2013-07-25 17:51:42
回答 1查看 66关注 0票数 0

我可以有一个双重嵌套的对象文字,如下面的“成分”的值(语法正确吗)?

代码语言:javascript
复制
recipes = [    
            {name: 'Zucchini Muffins',  url: 'pdfs/recipes/Zucchini Muffins.pdf', 
            ingredients: [{name: 'carrot', amount: 13, unit: 'oz' },
                          {name: 'Zucchini', amount: 3, unit: 'sticks'}]
            } 
            ];

如果是这样,我将如何访问“成分”对象的“单位”值?

我能做这样的事吗?

psuedocode

代码语言:javascript
复制
for each recipes as recipe
       print "this recipe requires" 
         for each recipe.ingredients as ingredients
            ingredients.amount + " " + ingredients.unit;

(我正在考虑使用javascript)

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-07-25 18:18:54

以下是从这个数组(这是一只小提琴)中获取所需的所有信息的方法:

代码语言:javascript
复制
function printRecipes(recipeList) {
    for(var i = 0; i < recipeList.length; i++) { //loop through all recipes
        var recipe = recipeList[0], //get current recipe
            ingredients = recipe.ingredients; //get all ingredients
        console.log("This recipe is named", recipe.name, "and can be accessed via", recipe.url);
        console.log("These are the ingredients:");
        for(var j = 0; j < ingredients.length; j++) { //loop through all ingredients of current recipe
            var ingredient = ingredients[j]; //get current ingredient
            console.log("You need", ingredient.amount, ingredient.name + "(s)", "mesured in", ingredient.unit);
        }
        console.log("Finished recipe", name + "'s", "ingredient list, passing to next recipe!");
    }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17865280

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档