The for loop in JavaScript is used to perform repeated operations on the elements of an iterable object. The syntax is for (initialization; condition; increment) { ... }. A for-of loop is a more concise syntax for iterating over each element of an iterable object, with the syntax for (element of iterable) { ... }.
The for
for loop in JS is a commonly used control structure in JavaScript, which is used to Iterate elements in objects (such as arrays and strings) to perform repeated operations. The syntax is as follows:
<code class="javascript">for (initialization; condition; increment) { // 要执行的代码 }</code>
Among them:
Example
Consider an arraynumbers = [1, 2, 3, 4, 5]
. We can use a for loop Perform the following operations for each number in the array:
<code class="javascript">for (let i = 0; i < numbers.length; i++) { console.log(numbers[i]); }</code>
Output:
<code>1 2 3 4 5</code>
In this example:
initialization (let i = 0 )
: Initialize loop variable i
to 0. condition (i < numbers.length)
: The loop continues to execute as long as i
is less than the array length. increment (i )
: Increment i
by 1 after each iteration. The for loop also provides a more concise syntax called the for-of loop. It is used to iterate over each element of an iterable object, and the syntax is as follows:
<code class="javascript">for (element of iterable) { // 要执行的代码 }</code>
The above example using a for-of loop can be rewritten as:
<code class="javascript">for (let number of numbers) { console.log(number); }</code>
Both loop syntaxes can achieve the same effect, but the for-of loop is more concise and does not require explicit declaration of the loop variable when accessing the array index is required.
The above is the detailed content of What does for mean in js. For more information, please follow other related articles on the PHP Chinese website!