> Apex中文手册 > 类似Java的for循环

Java Like For Loop

在Apex中有传统的类似于Java的for循环。

语法:
for (init_stmt; exit_condition; increment_stmt) { code_block }

流程图:

类似Java的for循环

示例:
我们的例子使用传统的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 the 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运行时引擎按顺序执行以下步骤:

1、执行循环的init_stmt组件。 注意,可以在此语句中声明和/或初始化多个变量。
2、执行exit_condition检查。 如果为true,循环继续。 如果为false,则循环退出。
3、执行code_block。 我们的代码块是打印数字。
4、执行increment_stmt语句。 它将每次增加。
5、返回步骤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) }; 

注意事项:
1、我们不能在迭代它时修改集合。 假设你正在遍历列表“ListOfInvoices”,然后在迭代时不能修改同一列表中的元素。
2、您可以在迭代时在原始列表中添加元素,但是您必须在迭代时将元素保留在临时列表中,然后将这些元素添加到原始列表。
上一篇:
下一篇: