迭代器
使用集合让一切井井有条 根据您的偏好保存内容并对其进行分类。
迭代器是一种常见的编程模式,用于在以下情况下遍历对象列表:
- 一开始可能并不知道列表的大小。
- 一次将整个列表加载到内存中可能会导致资源消耗过多。
迭代器公开了两种方法:boolean hasNext()
和 Object next()
。Google Ads 脚本使用迭代器模式提取 Google Ads 实体。
在功能上,迭代器与常规数组没有太大差异,并且可以使代码更简洁。对比遍历数组的代码:
for (var i = 0; i < myArray.length; i++) {
let myObject = myArray[i];
}
使用遍历迭代器的代码:
while (myIterator.hasNext()) {
let myObject = myIterator.next();
}
以下代码演示了如何对账号中的所有广告系列使用迭代器:
var campaignIterator = AdsApp.campaigns().get();
while (campaignIterator.hasNext()) {
let campaign = campaignIterator.next();
console.log(`${campaign.getName()}; active? ${campaign.isEnabled()}; ` +
`budget=${campaign.getBudget().getAmount()}`);
}
您还可以使用内置的 JavaScript 迭代:
for (const campaign of AdsApp.campaigns()) {
console.log(`${campaign.getName()}; active? ${campaign.isEnabled()}; ` +
`budget=${campaign.getBudget().getAmount()}`);
}
将 withLimit()
应用于选择器不会更改 totalNumEntities()
的值。以下代码段中的 x
和 y
将具有相同的值:
var x = AdsApp.keywords().get().totalNumEntities();
var y = AdsApp.keywords().withLimit(5).get().totalNumEntities();
如需获取 Google Ads 实体的迭代器,您必须先构建一个选择器。
如未另行说明,那么本页面中的内容已根据知识共享署名 4.0 许可获得了许可,并且代码示例已根据 Apache 2.0 许可获得了许可。有关详情,请参阅 Google 开发者网站政策。Java 是 Oracle 和/或其关联公司的注册商标。
最后更新时间 (UTC):2025-03-29。
[[["易于理解","easyToUnderstand","thumb-up"],["解决了我的问题","solvedMyProblem","thumb-up"],["其他","otherUp","thumb-up"]],[["没有我需要的信息","missingTheInformationINeed","thumb-down"],["太复杂/步骤太多","tooComplicatedTooManySteps","thumb-down"],["内容需要更新","outOfDate","thumb-down"],["翻译问题","translationIssue","thumb-down"],["示例/代码问题","samplesCodeIssue","thumb-down"],["其他","otherDown","thumb-down"]],["最后更新时间 (UTC):2025-03-29。"],[[["Iterators in Google Ads scripts are used to efficiently process lists of objects, especially when dealing with large or unknown-sized datasets, by fetching entities one at a time."],["They offer two primary methods, `hasNext()` to check for more items and `next()` to retrieve the next item, similar to how arrays are traversed but without loading the entire list into memory."],["The Google Ads scripts utilize the Iterator pattern for accessing and manipulating various Google Ads entities like campaigns, allowing for streamlined processing and resource management."],["While applying `withLimit()` to a selector constrains the number of fetched entities, it doesn't affect the overall count obtained via `totalNumEntities()`."],["To retrieve an Iterator of Google Ads objects, you first need to define a Selector that specifies the desired entities and their properties."]]],[]]