2013-07-25 45 views
0

我可以有一個雙重嵌套的對象字面值,如下面的「成分」的值(是正確的語法)?你可以有一個雙重嵌套的對象文字?

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的)

+1

你可以讓它像那樣構造,但是; '食譜'是_Array_。 'recipes [0]'是一個_Object_。 '食譜[0] .ingredients'是_Array_。 'recipes [0] .ingredients [0]'是另一個_Object_。 '食譜[0] .ingredients [0] .unit'是'「oz」'。另外,['for each..in'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for_each...in)被折舊並且不明智無論如何,在_Array_上使用。 –

+0

爲什麼不嘗試並找出答案? –

+0

@paul啊,好吧,那是我的直覺。感謝每個人的頭像。 @ Matt Burland對語法尚不確定,我想在深入細節之前對概念進行概述。 – LazerSharks

回答

1

這是你可以讓你從這個陣列需要的所有相關信息(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!"); 
    } 
} 
+0

太棒了!這是完全合理的。謝謝,upvoted。你碰巧有一個快速的想法如何使用'angularjs'來添加成分量? – LazerSharks

+0

不,我不知道這一點,你應該閱讀文檔,他們做得很好;) –

相關問題