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
广告