2015-07-11 19 views
0

以下是角度控制器中的功能。 「alert(coffee.brand)」或數組的任何其他部分打印「undefined」,顯然它不是。奇怪的部分是,undefined在for循環中輸出正確的次數,所以它知道數組已被填充,看起來似乎無法讀取數據。想法?提前致謝!角度控制器陣列即使我剛剛定義它爲空

$scope.activate = function(id){ 


      $scope.coffees = 
    [ 
    {'id': 1, 
    'brand': 'Folgers', 
    'name': 'Regular', 
    'country': 'America', 
    'reviews': [ 
      {'rating': 3, 
      'comment': "gross", 
      'reviewer': "James" 
      } 
    ] 
    }, 
    {'id': 2, 
    'brand': 'Starbucks', 
    'name': 'Mocha', 
    'country': 'America', 
    'reviews': [ 
    {'rating': 7, 
    'comment': 'insane!', 
    'reviewer': 'Bob' 
    }, 
    {'rating': 5, 
    'comment': 'solid...', 
    'reviewer': 'Joe' 
    } 
    ] 
    } 
    ]; 

      for (coffee in $scope.coffees){      

        alert (coffee.brand); 
        if (coffee.id == id){ 
          $scope.currCoffee = coffee; 
          alert("here") 
          alert ($scope.currCoffee.id); 
        } 
      } 

    }; 
+1

咖啡是關鍵不是對象本身,所以像'$ scope.coffees [咖啡]' – vinayakj

回答

-1

咖啡是鑰匙不是對象本身,所以像$ scope.coffees [咖啡]。

欲瞭解更多信息

  • for...in

    它遍歷枚舉自己和枚舉繼承的屬性。

+0

爲什麼downvote .. atleast放置評論,所以也可以理解 – vinayakj

1

您正在使用for in循環不正確。它不會遍歷數組中的元素,而是遍歷對象的屬性名稱。在你的情況,因爲你使用的是隱式數字索引數組,這將是更好地使用正常for循環,就像這樣:

for (var i = 0; i < $scope.coffees.length; i++) {   
    var coffee = $scope.coffees[i];    
    alert (coffee.brand); 
    if (coffee.id == id){ 
     $scope.currCoffee = coffee; 
     alert("here") 
     alert ($scope.currCoffee.id); 
    } 
} 

有關for in循環的更多信息,請參見上的文檔在MDN

相關問題