课程表

Apex课程

工具箱
速查手册

Apex - 类似Java的循环

当前位置:免费教程 » 程序设计 » Apex
在Apex中有传统的类似于Java的for循环。

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

流程图:

流程图

示例:
我们的例子使用传统的for循环:
  1. //The same previous example using For Loop
  2. //initializing the custom object records list to store the Invoice Records
  3. List<apex_invoice__c> PaidInvoiceNumberList = new List<apex_invoice__c>();
  4. 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
  5. List<string> InvoiceNumberList = new List<string>();//List to store the Invoice Number of Paid invoices
  6. 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.
  7. if (PaidInvoiceNumberList[i].APEX_Status__c == 'Paid') {//Condition to check the current record in context values
  8. System.debug('Value of Current Record on which Loop is iterating is '+PaidInvoiceNumberList[i]);//current record on which loop is iterating
  9. InvoiceNumberList.add(PaidInvoiceNumberList[i].Name);//if Status value is paid then it will the invoice number into List of String
  10. }
  11. }
  12. 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,语法:
  1. //this will print the numbers from 1 to 100}
  2. for (Integer i = 0, j = 0; i < 100; i++) { System.debug(i+1) };

注意事项:
1、我们不能在迭代它时修改集合。 假设你正在遍历列表“ListOfInvoices”,然后在迭代时不能修改同一列表中的元素。
2、您可以在迭代时在原始列表中添加元素,但是您必须在迭代时将元素保留在临时列表中,然后将这些元素添加到原始列表。
转载本站内容时,请务必注明来自W3xue,违者必究。
 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号