目录

Java-like for循环

Apex中有一个传统的类似Java的for循环。

语法 (Syntax)

for (init_stmt; exit_condition; increment_stmt) { code_block }

流程图 (Flow Diagram)

Apex For Loop

例子 (Example)

请考虑以下示例以了解传统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);

执行步骤 (Execution Steps)

执行此类型的for loop ,Apex运行时引擎执行以下步骤 -

  • 执行循环的init_stmt组件。 请注意,可以在此语句中声明和/或初始化多个变量。

  • 执行exit_condition检查。 如果为true,则循环继续;如果为false,则循环退出。

  • 执行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) };

考虑因素(Considerations)

执行此类型的for loop语句时,请考虑以下几点。

  • 迭代时我们无法修改集合。 假设您正在迭代列表'ListOfInvoices' ,那么在迭代时您无法修改同一列表中的元素。

  • 您可以在迭代时在原始列表中添加元素,但是您必须在迭代时将元素保留在临时列表中,然后将这些元素添加到原始列表中。

↑回到顶部↑
WIKI教程 @2018