2014-04-29 36 views
-2

我想使用下面的代碼做一個簡單的加法,但由於某種原因結果是簡單的字符串連接,而不是算術加法。有人可以告訴我我在這裏錯過了什麼以及如何解決這個問題?謝謝AngularJS簡單加法不工作

$scope.budget = localStorageService.get('budget'); //this returns 5000 
$scope.toBeAdded = localStorageService.get('newAddition'); //this return 500 

$scope.NewBudget = $scope.budget + $scope.toBeAdded; //return 5000500 instead of 5500 

回答

1

localStorage存儲爲字符串。如果你需要一個整數,你需要用返回值parseInt。例如:

$scope.budget = parseInt(localStorageService.get('budget'), 10); //this returns 5000 
$scope.toBeAdded = parseInt(localStorageService.get('newAddition'), 10); //this return 500 

$scope.NewBudget = $scope.budget + $scope.toBeAdded; 

如果您期待十進制數,當然您需要使用parseFloat而不是parseInt。

+1

不要忘記在使用parseInt時添加基數。 – Stuart

1

推測$ scope.budget和$ scope.toBeAdded被返回爲字符串而不是整數;不過,我認爲您沒有分享足夠的代碼來診斷原因。嘗試轉換:

$scope.NewBudget = Number($scope.budget) + Number($scope.toBeAdded) 

它使用Number函數將字符串轉換爲數字。

1

做到這一點把他們變成數字:

$scope.budget = parseInt(localStorageService.get('budget'), 10); 
$scope.toBeAdded = parseInt(localStorageService.get('newAddition'), 10); 

這將確保這些值作爲整數傳遞。不要忘記parseInt()結束時的基數。