简体   繁体   中英

GAS/ Javascript giving wrong figures when summing up numbers

My Javascript/GAS code uses the user ID to call for time entries via API for a specific date range (1 week) and sum up the hours. These time entries are saved in an array and then summed up. The first 50 additions on the log are correct but as you go through the list you realize wrong summed figures and long decimal places. What could be wrong and what can I do to solve this. Here is my code:

var TKF_URL = 'https://api.10000ft.com/api/v1/';
var TKF_AUTH = 'auth'
var TKF_PGSZ = 2500
var from = '2020-01-06'
var to = '2020-01-22'
var options = {
    method: 'get',
    headers: {
        Authorization: 'Bearer ' + TKF_AUTH
    }
};

function getUsers() {
    var userarray = [];
    var lastpage = false;
    var page = 1;
    do {

        // gets 10kft data   
        var users = read10k_users(page);

        // writes data from current page to array   
        for (var i in users.data) {
            var rec = {};

            // pushing of mandatory data     
            rec.id = users.data[i].id;
            rec.display_name = users.data[i].display_name;
            rec.email = users.data[i].email;
            userarray.push(rec);
        }

        // checks if this is the last page (indicated by paging next page link beeing null   
        if (users.paging.next != null) {
            lastpage = false;
            var page = page + 1;
        } else {
            lastpage = true;
        }
    }
    while (lastpage == false);
    return (userarray);


    return (userarray);

}

function read10k_users(page) {

    var endpoint = 'users?';

    var url = TKF_URL + endpoint + 'per_page=' + TKF_PGSZ + '&auth=' + TKF_AUTH + '&page=' + page;
    var response = UrlFetchApp.fetch(url, options);
    var json = JSON.parse(response);

    //Logger.log(json.data)
    return (json);
}


function showTimeData() {

    var users = getUsers()
    var endpoint = 'users/';
    var time_array = [];



    for (var i = 0; i < users.length; i++) {

        var total_hours = 0;

        // Logger.log(users[i].id)
        var url = 'https://api.10000ft.com/api/v1/users/' + users[i].id + '/time_entries?fields=approvals' + '&from=' + from + '&to=' + to + '&auth=' + TKF_AUTH;
        var response = UrlFetchApp.fetch(url, options);

        var info = JSON.parse(response.getContentText());

        var content = info.data;

        for (var j = 0; j < content.length; j++) {

            total_hours += content[j].hours;

            //     }
            //     
            //       if(total_hours < 35){
            //    
            //          sendMail(user[i]);
            //      
            //       }

            Logger.log('User name: ' + users[i].display_name + ' ' + 'User id: ' + users[i].id + '  ' + 'total hours: ' + total_hours)



        }

    }

    function sendMail(user) {



        var emailAddress = user.email;
        var message = 'Dear ' + user.display_name + 'Your timesheets is incomplete , please visist 10k Ft and commlete your timesheet'
        var subject = 'TimeSheet';

        MailApp.sendEmail(emailAddress, subject, message);

    }
}

Log results

在此处输入图片说明

You have total_hours declared outside of your loop. So what you are doing is calculating the total hours all workers combined, not total hours per worker.

(removed a lot of code to show only the important parts for your bug)

function showTimeData() {
  var users = getUsers()
  var total_hours = 0; // you declare the variable here

  for (var i = 0; i < users.length; i++) {
    var content = info.data;

    // Calculate the sum for current user
    for (var j = 0; j < content.length; j++) {    
      total_hours += content[j].hours;    
    }

    // Check if total_hours for ALL workers is less than 35 
    if (total_hours < 35) sendMail(user[i]);

    // total_hours is not reset, so the sum is used in next iteration.
  }
}

Move the declaration of total_hours to inside the loop, or reset it to zero.

function showTimeData() {  
  for (var i = 0; i < users.length; i++) {
    var total_hours = 0; // you declare the variable here
  }
}

Your loop should look something like this:

for (var i = 0; i < users.length; i++) {
  var total_hours = 0;

  var url = "https://api.10000ft.com/api/v1/users/" + users[i].id + "/time_entries?fields=approvals" + "&from=" + from + "&to=" + to + "&auth=" + TKF_AUTH;
  var response = UrlFetchApp.fetch(url, options);

  var info = JSON.parse(response.getContentText());

  var content = info.data;

  for (var j = 0; j < content.length; j++) {
    total_hours += content[j].hours;
  }

  if (total_hours < 35) {
    sendMail(user[i]);
  }

  Logger.log("User name: " + users[i].display_name + " " + "User id: " + users[i].id + "  " + "total hours: " + total_hours);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM