迭代器
透過集合功能整理內容
你可以依據偏好儲存及分類內容。
疊代器是常見的程式設計模式,用於在以下情況下遍歷物件清單:
- 無法一開始就知道清單大小。
- 一次將整個清單載入記憶體可能會消耗過多資源。
迭代器會公開兩個方法: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 實體的迭代器,您必須先建構選取器。
除非另有註明,否則本頁面中的內容是採用創用 CC 姓名標示 4.0 授權,程式碼範例則為阿帕契 2.0 授權。詳情請參閱《Google Developers 網站政策》。Java 是 Oracle 和/或其關聯企業的註冊商標。
上次更新時間: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"]],["上次更新時間: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."]]],[]]