Saya memiliki kode berikut:

$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;
}

Tapi saya tidak tahu mengapa itu tidak berhasil. Jika bpr misalnya 50 dan 43.1034, maka log output di konsol seperti ini, iTotal:"050.000043.1034"

Saya baru mengenal JavaScript dan saya memulainya langsung dengan AngularJS. Jadi tolong bantu saya dengan operator aritmatika di JS. Terima kasih.

0
TheCleverIdiot 8 Agustus 2017, 09:30

2 jawaban

Jawaban Terbaik
$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;
}
2
Aks1357 8 Agustus 2017, 06:48

Anda menambahkan i di dalam loop. Hapus duplikat i dan saya menduga $scope.order[i]['baseprice'] Anda bukan bilangan bulat. Jadi konversikan ke integer menggunakan 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;
    }
1
Vivz 8 Agustus 2017, 06:46