Apex - 類Java的For迴圈



Apex 中提供了傳統的類似 Java 的for迴圈。

語法

for (init_stmt; exit_condition; increment_stmt) { code_block }

流程圖

Apex For Loop

示例

請考慮以下示例以瞭解傳統 for 迴圈的用法:

// The same previous example using For Loop
// initializing the custom object records list to store the Invoice Records
List<apex_invoice__c> PaidInvoiceNumberList = new List<apex_invoice__c>();

PaidInvoiceNumberList = [SELECT Id,Name, APEX_Status__c FROM APEX_Invoice__c WHERE 
   CreatedDate = today];

// this is SOQL query which will fetch the invoice records which has been created today
List<string> InvoiceNumberList = new List<string>();

// List to store the Invoice Number of Paid invoices
for (Integer i = 0; i < paidinvoicenumberlist.size(); i++) {
   
   // this loop will iterate on the List PaidInvoiceNumberList and will process
   // each record. It will get the List Size and will iterate the loop for number of
   // times that size. For example, list size is 10.
   if (PaidInvoiceNumberList[i].APEX_Status__c == 'Paid') {
      
      // Condition to check the current record in context values
      System.debug('Value of Current Record on which Loop is iterating is 
         '+PaidInvoiceNumberList[i]);
      
      //current record on which loop is iterating
      InvoiceNumberList.add(PaidInvoiceNumberList[i].Name);
      // if Status value is paid then it will the invoice number into List of String
   }
}

System.debug('Value of InvoiceNumberList '+InvoiceNumberList);

執行步驟

執行此類for迴圈時,Apex 執行時引擎將執行以下步驟:

  • 執行迴圈的init_stmt部分。請注意,可以在此語句中宣告和/或初始化多個變數。

  • 執行exit_condition檢查。如果為真,則迴圈繼續;如果為假,則迴圈退出。

  • 執行code_block。我們的程式碼塊用於列印數字。

  • 執行increment_stmt語句。它將每次遞增。

  • 返回步驟 2。

另一個示例,以下程式碼將數字 1-100 輸出到除錯日誌。請注意,包含了額外的初始化變數 j 來演示語法

//this will print the numbers from 1 to 100}
for (Integer i = 0, j = 0; i < 100; i++) { System.debug(i+1) };

注意事項

執行此類for迴圈語句時,請考慮以下幾點。

  • 在迭代集合時,我們不能修改集合。假設您正在迭代列表'ListOfInvoices',那麼在迭代過程中,您不能修改同一列表中的元素。

  • 您可以在迭代時向原始列表新增元素,但是您必須在迭代時將元素儲存在臨時列表中,然後將這些元素新增到原始列表。

apex_loops.htm
廣告