Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For-each loop in google apps script

How do you create a for-each loop in Google Apps Script?

I'm writing an email script with GAS, and I'd like to iterate through an array using a for-each loop, rather than a regular for-loop.
I've already seen this answer, but the object is undefined, presumably because the for loop doesn't work.

// threads is a GmailThread[] for (var thread in threads) {   var msgs = thread.getMessages();   //msgs is a GmailMessage[]   for (var msg in msgs) {     msg.somemethod(); //somemethod is undefined, because msg is undefined.   } } 


(I'm still new to javascript, but I know of a for-each loop from java.)

like image 668
phlaxyr Avatar asked Oct 11 '17 16:10

phlaxyr


1 Answers

Update: See @BBau answer below https://stackoverflow.com/a/60785941/5648223 for update on Migrating scripts to the V8 runtime.

 In Google Apps Script: When using "for (var item in itemArray)", 'item' will be the indices of itemArray throughout the loop (0, 1, 2, 3, ...).  When using "for each (var item in itemArray)", 'item' will be the values of itemArray throughout the loop ('item0',  'item1', 'item2', 'item3', ...). 

Example:

function myFunction() {   var arrayInfo = [];      arrayInfo.push('apple');   arrayInfo.push('orange');   arrayInfo.push('grapefruit');      Logger.log('Printing array info using for loop.');   for (var index in arrayInfo)   {     Logger.log(index);   }   Logger.log('Printing array info using for each loop.');   for each (var info in arrayInfo)   {     Logger.log(info);   } } 

Result:

      [17-10-16 23:34:47:724 EDT] Printing array info using for loop.     [17-10-16 23:34:47:725 EDT] 0     [17-10-16 23:34:47:725 EDT] 1     [17-10-16 23:34:47:726 EDT] 2     [17-10-16 23:34:47:726 EDT] Printing array info using for each loop.     [17-10-16 23:34:47:727 EDT] apple     [17-10-16 23:34:47:728 EDT] orange     [17-10-16 23:34:47:728 EDT] grapefruit  
like image 91
Branden Huggins Avatar answered Sep 24 '22 19:09

Branden Huggins