Google Apps脚本中的每个循环 [英] For-each loop in google apps script

查看:58
本文介绍了Google Apps脚本中的每个循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Google Apps脚本编写简单易懂的电子邮件机器人处理程序.
说有很多东西.
我想使用for-each循环遍历数组.
(这很麻烦,每次迭代数组时都写for(var i=0;i<threads.length;i++).)
我正在寻找Google Apps脚本的for-each循环.
我已经看到了答案,但是该对象未定义,大概是因为for循环不起作用.

I'm writing a straightforward email bot handler thing using Google Apps Script.
Say there's an array of something.
I want to iterate through the array using a for-each loop.
(It's tedious, writing for(var i=0;i<threads.length;i++) everytime I iterate through an array.)
I'm looking for a for-each loop for google apps script.
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.
  }
}


(我对javascript还是很陌生,但是我知道Java的for-each循环.)


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

推荐答案

更新:请参见下面的@BBau答案 https://stackoverflow. com/a/60785941/5648223 ,以获取有关将脚本迁移到V8运行时的更新.

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', ...).

示例:

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

结果:



    [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

这篇关于Google Apps脚本中的每个循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆