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

Can you have a doubly nested object literal?

本文关键字:对象 文字 嵌套 有一个      更新时间:2023-09-26

我可以有一个像下面的"components"值那样的双重嵌套对象文字吗(语法正确吗)?

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

如果是,我将如何访问"成分"对象的"单位"值?

我能做这样的事吗?

伪码

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

(我正在考虑使用javascript)

这就是如何从这个数组中获得所需的所有信息(这里是一个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!");
    }
}