2017-08-08 68 views
0

我有以下代碼:麻煩與算術運算符在AngularJS

$scope.showTotal = function() { 
    $scope.pT = []; 
    var iT = 0; 
    for (var i = 0; i < $scope.od.length; i++) { 
     console.log($scope.od[i]['bpr']); 
     iT += $scope.od[i]['bpr']; 
     // also tried this -> iT = iT + $scope.od[i]['bpr'] 
    } 
    $scope.pT.push({iTotal: iT}); 
    console.log($scope.popupTotals); 
    $scope.showPopupNow = true; 
} 

但我不知道爲什麼它不工作。 如果bpr是例如50和43.1034,那麼它在控制檯中記錄輸出如下,iTotal:"050.000043.1034"

我是JavaScript新手,我直接使用AngularJS啓動它。 所以請幫助我在JS中的算術運算符。 謝謝。

+0

爲什麼你複製我++在年底的整數? –

+0

刪除它。 @AlexanderAnikeev –

+0

你有什麼類型的對象$ scope.order [i] ['baseprice']?如果它字符串,你必須parseFloat。 –

回答

2
$scope.showTotal = function() { 
    $scope.popupTotals = []; 
    var itemtotal = 0; 
    for (var i = 0; i < $scope.order.length; i++) { 
     console.log($scope.order[i]['baseprice']); 
     itemtotal += parseFloat($scope.order[i]['baseprice']); 
     // parseFloat will convert string to number and add the number instead of concatenating the strings 
    } 
    $scope.popupTotals.push({itembasetotal : itemtotal}); 
    console.log($scope.popupTotals); 
    $scope.showPopupNow = true; 
} 
+0

非常感謝。有效。 –

+0

@RahulJain - 歡迎光臨! – Aks1357

1

你正在遞增我內循環。刪除重複的我,我懷疑你的$scope.order[i]['baseprice']是不是一個整數。因此,將其轉換爲使用parseFloat

$scope.showTotal = function(){ 
     $scope.popupTotals = []; 
     var itemtotal = 0; 
     for (var i = 0; i<$scope.order.length; i++){ 
      console.log($scope.order[i]['baseprice']); 
      itemtotal += parseFloat($scope.order[i]['baseprice']); 
      //also tried this -> itemtotal = itemtotal + $scope.order[i]['baseprice'] 
      //i++; No need to increment here 
     } 
     $scope.popupTotals.push({itembasetotal : itemtotal}); 
     console.log($scope.popupTotals); 
     $scope.showPopupNow = true; 
    } 
+0

仍然是相同的結果。 –

+0

你的$ scope.order [i] ['baseprice']是一個字符串嗎?嘗試使用parseFloat更新答案 – Vivz