Pernyataan Iterasi Ekstensi ECMAScript

Pernyataan iterasi disebut juga pernyataan perulangan, yang menyatakan suatu grup perintah untuk diulang-ulang sampai terpenuhi beberapa kondisi.

Perulangan biasanya digunakan untuk mengiterasi nilai array (sebabnya dinamai seperti itu) atau melaksanakan tugas aritmatika berulang.

Bagian ini memperkenalkan empat jenis pernyataan iterasi yang disediakan ECMAScript.

do-while statement

The do-while statement is a post-test loop, which means that the exit condition is calculated after the code inside the loop is executed. This means that the loop body will be executed at least once before the expression is calculated.

The syntax is as follows:

do {statement} while (expression);

Example:

var i = 0;
do {i += 2;} while (i < 10);

while statement

The while statement is a pre-test loop. This means that the exit condition is calculated before the code inside the loop is executed. Therefore, the loop body may not be executed at all.

The syntax is as follows:

while (expression) statement

Example:

var i = 0;
while (i < 10) {
  i += 2;
}

for statement

The for statement is a pre-test loop, and it is possible to initialize variables and define code to be executed after the loop before entering the loop.

The syntax is as follows:

for (initialization; expression; post-loop-expression) statement

Note:post-loop-expression Semicolons cannot be written after this, otherwise it will not run.

Example:

iCount = 6;
for (var i = 0; i < iCount; i++) {
  alert(i);
}

This code defines a variable i with an initial value of 0. The for loop is entered only when the value of the condition expression (i < iCount) is true, so the loop body may not be executed. If the loop body is executed, then the post-loop expression is executed, and the variable i is iterated.

for-in statement

The for statement is a strict iteration statement used to enumerate the properties of an object.

The syntax is as follows:

for (property in expression) statement

Example:

for (sProp in window) {
  alert(sProp);
}

Here, the for-in statement is used to display all properties of the window object.

PropertyIsEnumerable() discussed earlier is a method specifically used in ECMAScript to indicate whether a property can be accessed using the for-in statement.