简体   繁体   中英

TypeError: Cannot call method “push” of undefined

I am attempting to modify a google-apps-script to create an event in google calendar to follow up on emails with certain labels. That side of it I will take care of. The issue I'm having is getting TypeError: Cannot call method "push" of undefined when attempting to run the script. I am not seeing the mistake here so any help would be greatly appreciated.

 function ReadEmails() {

  var thread, subject, body, from, 
      date, emails, index, event = [], i;

  var mySheet = SpreadsheetApp.getActiveSpreadsheet();  

  var LABEL = mySheet.getRange("D5").getValue();
  var TOTAL = mySheet.getRange("D7").getValue();

  emails = GmailApp.search("label:" + LABEL);  
  var count = emails.length;

  if (count == 0)
    return;

  if (count > TOTAL) 
    index = getIndex(TOTAL, 0, count);
  else {    
    for (i=0; i<count; i++)
      index.push(i);
  }

  for (i=0; i<TOTAL; i++) {

    var n = index[i];

    if (emails[n]) {

      thread    = emails[n].getMessages()[0];

      subject   = thread.getSubject();
      body      = processHTML(thread.getBody(), 250);
      link      = thread.getId();
      from      = thread.getFrom();
      date      = Utilities.formatDate(thread.getDate(), 
      Session.getTimeZone(), "MMM dd, yyyy");
      event     = 'Follow up with' + from + 'on'+ subject + ', Next Friday 
      at 1PM';

    CalendarApp.getDefaultCalendar().createEventFromDescription(event);
    Logger.log('Event ID: ' + event.getId());

    }
  }



}  

function getIndex(count, min, max) {
    var results = [], index;
    while ( count > 0) {
        randNumber = Math.round(min + Math.random() * (max - min));
        if (results.indexOf(randNumber) == -1) {
            results.push(randNumber);
            count--;
        }
    }
  return results;

As @Pointy pointed out, the value of index is undefined. Actually, all of your variables thread, subject, body, from, date, emails, index, event are undefined at first, since you're assigning two values to them, which I have never seen in any language reference.
Later, you're re-assigning all of them except index , but the initial assignment of [], i is syntactically wrong - hence the undefined .

Just declare and initialize index like this: var index = []; and you should be fine. The other variables you could initialize to null to make clear that you're gonna assign some proper values later on.

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