Apex - While 循环

只要给定条件为真,Apex 编程语言中的

while 循环语句就会重复执行目标语句。 这在某种程度上类似于 do-while 循环,但有一个主要区别。 只有当条件为 true 时才会执行代码块,但在 do-while 循环中,即使条件为 false,也会至少执行一次代码块。

语法

while (Boolean_condition) { execute_code_block }

流程图

Apex Wile 循环

这里 while 循环的关键点是循环可能永远不会运行。 当条件测试结果为假时,将跳过循环体并执行 while 循环后的第一条语句。

示例

在此示例中,我们将实现与 do-while 循环相同的场景,但这次使用 While 循环。 它将更新 10 条记录的描述。

//Fetch 20 records from database
List<apex_invoice_c> InvoiceList = [SELECT Id, APEX_Description_c,
   APEX_Status_c FROM APEX_Invoice_c LIMIT 20];
Integer i = 1;

//Update ONLY 10 records
while (i< 10) {
   InvoiceList[i].APEX_Description__c = 'This is the '+i+'Invoice';
   System.debug('Updated Description'+InvoiceList[i].APEX_Description_c);
   i++;
}

apex_loops.html