简体   繁体   English

你可以有一个双重嵌套的对象文字吗?

[英]Can you have a doubly nested object literal?

Can I have a doubly nested object literal like the value of "ingredients" below (is the syntax correct)? 我可以像下面的“ ingredients”的值那样使用双重嵌套的对象常量吗(语法正确)吗?

recipes = [    
            {name: 'Zucchini Muffins',  url: 'pdfs/recipes/Zucchini Muffins.pdf', 
            ingredients: [{name: 'carrot', amount: 13, unit: 'oz' },
                          {name: 'Zucchini', amount: 3, unit: 'sticks'}]
            } 
            ];

and if so, how would I access the "unit" value of the "ingredients" objects? 如果是这样,我将如何访问“成分”对象的“单位”值?

Could i do something like this? 我可以做这样的事情吗?

psuedocode 伪码

for each recipes as recipe
       print "this recipe requires" 
         for each recipe.ingredients as ingredients
            ingredients.amount + " " + ingredients.unit;

(I'm thinking of using javascript) (我正在考虑使用JavaScript)

This is how you can get all the infos you need from this array( here is a jsfiddle ): 这是您可以从此数组( 这是jsfiddle )中获取所需所有信息的方法

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!");
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM