【发布时间】:2017-10-11 16:40:59
【问题描述】:
如何在 Google Apps 脚本中创建 for-each 循环?
我正在使用 GAS 编写电子邮件脚本,我想使用 for-each 循环而不是常规的 for 循环来迭代数组。
我已经看过this的回答,但是对象是未定义的,大概是因为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 循环。)
【问题讨论】:
-
for (var thread of threads) { var msgs = thread.getMessages(); //msgs 是一个 GmailMessage[] for (var msg in msgs) { ... } }
-
for...in 迭代对象的键,而不是它的值。这种模式在 JS 中是不鼓励的,因为它将包含添加到数组的自定义原型。如果你想要一个更优雅的解决方案,我建议
thread.map(handleThread)或类似的东西 -
'在更高版本的 javaScript 中,forEach 方法被添加到 Array 对象中。 Google Apps 脚本使用的 JavaScript 引擎提供了这种模式。来自ramblings.mcpher.com/Home/excelquirks/gooscript/loops。请参阅下面的答案。
-
好的,我已经纠正了
标签: javascript google-apps-script