gpt4 book ai didi

javascript - 谷歌应用程序脚本中的每个循环

转载 作者:可可西里 更新时间:2023-11-01 01:45:59 24 4
gpt4 key购买 nike

如何在 Google Apps 脚本中创建 for-each 循环?

我正在使用 GAS 编写电子邮件脚本,我想使用 for-each 循环而不是常规的 for 循环来遍历数组。
我已经看过了this answer,但是对象是未定义的,大概是因为 for 循环不起作用。

// 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 循环。)

最佳答案

更新:请参阅下面的@BBau 回答https://stackoverflow.com/a/60785941/5648223有关将脚本迁移到 V8 运行时的更新。

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

结果:

    [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

关于javascript - 谷歌应用程序脚本中的每个循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46693496/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com