困在控制器的傻循环中

时间:2018-05-28 16:23:46

标签: angularjs

我有这个功能:

(.*)/Store/SomeThing/(.*)

&#39; 2&#39; in loop可以$scope.showCurrencyT = function(invCurrency){ for (i=0; i<2; i++) { console.log("i is " +i); if (parseInt($scope.pageInfo.currencies[i].currencyCode) === parseInt(invCurrency) ) { console.log('passed '+ i + ' ' + $scope.pageInfo.currencies[i].currencyCode ) var symbol = $scope.pageInfo.currencies[i].symbol console.log(symbol); } else { console.log(i +" else") var symbol = invCurrency } } console.log("final symbol is " + symbol) return symbol } 实际

$scope.pageInfo.currencies.length看起来像这样:

$scope.pageInfo.currencies object

当我在视野中传递时:

 [  
   {  
      "_id":"59e5d2ad57acbb22bce66482",
      "name":"US Dollar",
      "nameInOriginalLanguage":"US Dollar",
      "nameStringId":"806c1313-a9f4-53bc-8f20-6897aae76d0a",
      "symbol":"USD",
      "currencyCode":"840",
      "__v":0
   },
   {  
      "_id":"59e5d2ec57acbb22bce66484",
      "name":"Turkish Lira",
      "nameInOriginalLanguage":"Türk Lirası",
      "nameStringId":"e072dece-4e18-d830-06b3-9e789a3b5240",
      "symbol":"TRY",
      "currencyCode":"949",
      "__v":0
   }
]

我进入控制台:

  

最终符号为840

但是当我传递{{showCurrencyT("840")}} 时,我得到的最终符号为TRY

应该返还美元840,我不明白发生了什么!

1 个答案:

答案 0 :(得分:1)

你不需要在这里使用for循环,你可以简单地使用array.find()方法来找到完全匹配的值,如下所示,

$scope.showCurrencyT = function(invCurrency){
   var result = $scope.pageInfo.currencies.find(t=>t.currencyCode === invCurrency);
   return result.symbol;
}