質問

Can I have a doubly nested object literal like the value of "ingredients" below (is the syntax correct)?

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)

役に立ちましたか?

解決

This is how you can get all the infos you need from this array(here is a 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帰属
所属していません StackOverflow
scroll top